-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_env
executable file
·1148 lines (1049 loc) · 35.6 KB
/
get_env
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# get_env - a program for downloading and managing of distributed dotfiles and user environment.
# Copyright (C) 2013 Björn Bohman
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see {http://www.gnu.org/licenses/}.
#
set -u
# This functions starts the script so all functions don't need to be sourced before exiting.
depends() {
local app=""
for app in ${@}; do
if ! which ${app} >/dev/null; then
echo "Missing program \"${app}\""
exit 1
fi
done
}
depends awk cat cp diff egrep fold grep host logger mkdir rm rsync sed tac tput unzip wget
# Verify vi have needed version of BASH to be able to continue.
dependBashVersion() {
local depMajor="$1"
local depMinor="$2"
local depNotMet=""
if [ "${BASH_VERSINFO[0]}" -lt "${depMajor}" ]; then
depNotMet="1"
# Major not met
fi
if [ "${BASH_VERSINFO[0]}" -eq "${depMajor}" ]; then
if [ "${BASH_VERSINFO[1]}" -lt "${depMinor}" ]; then
# Minor not met
depNotMet="1"
fi
fi
if [ -n "${depNotMet}" ]; then
echo "Need BASH version ${depMajor}.${depMinor} or later"
exit 1
fi
}
# Depend on BASH 4.3 because use of "local -n" in reverseArray()
dependBashVersion 4 3
# The script name
myName=$(basename ${0})
# The absolute script name, on server, and default name.
myAbsoluteName=get_env
# Configuration file
confFile=~/"${myName}".conf
# The directory program was started in
myStartDirectory=$(pwd)
# Colors
red='\033[0;31m'
boldRed='\033[1;31m'
purple='\033[0;35m'
cyan='\033[0;36m'
yellow='\033[1;33m'
white='\033[1;37m'
blue='\033[1;34m'
green='\033[1;32m'
end='\033[0m'
# Values for Warnings and Info text
tput=$(which tput)
position=$(($(${tput} cols) - 10))
tprint="${tput} hpa ${position}"
# Colors for Info and Warning texts.
info=${yellow}
warning=${red}
downloadDir=$(mktemp -d /tmp/${myName}.XXXXXX)
debug=""
debugLog=""
offline=""
createdDirs=""
updatedFiles=""
newFiles=""
dryrun=""
dryrunCreatedDirs=""
dryrunUpdatedFiles=""
dryrunNewFiles=""
noGet_envUpdate=""
promptSourceConfigFile=""
quietMode=""
reportUrl=""
startBranch=""
dateFormat='%Y-%m-%d %H:%M:%S'
ddate=$(date +"${dateFormat}")
### Functions
# Function to print GNU disclaimer
gnuLicense() {
dbg "${FUNCNAME}() was called, arg: ${*}"
cat <<EOF
${myName} Copyright (C) 2013 Björn Bohman
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see [http://www.gnu.org/licenses/].
For more information see: https://github.com/spetzreborn/get_env
EOF
dbg "${FUNCNAME}() leaving function"
}
# Function for word wrapping
# Arg: Optional [-e|-n] "Message"
# -e = extended. "echo -e" Needed to show colors.
# -n = no newline. "echo -n"
foldIt() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local maxwidth=$(($(tput cols) - 15))
local extended=""
local noNewline=""
while [ ${#} -gt 1 ]; do
case "${1}" in
-e)
dbg "Set extended for foldIt()"
extended="yes"
shift
;;
-n)
dbg "Set noNewline for foldIt()"
noNewline="yes"
shift
;;
-en)
dbg "Set extended and noNewline for foldIt()"
extended="yes"
noNewline="yes"
shift
;;
-ne)
dbg "Set extended and noNewline for foldIt()"
extended="yes"
noNewline="yes"
shift
;;
echo)
shift
;;
esac
done
local input="${1}"
if [ -z "${quietMode}" ]; then
if [ -z "${extended}" ] && [ -z ${noNewline} ]; then
echo "${input}" | fold -s -w ${maxwidth}
dbg "$(echo ${input})"
elif [ -n "${extended}" ] && [ -z ${noNewline} ]; then
echo -e "${input}" | fold -s -w ${maxwidth}
dbg "$(echo -e ${input})"
elif [ -z "${extended}" ] && [ -n ${noNewline} ]; then
echo -n "${input}" | fold -s -w ${maxwidth}
dbg "$(echo -n ${input})"
elif [ -n "${extended}" ] && [ -n ${noNewline} ]; then
echo -en "${input}" | fold -s -w ${maxwidth}
dbg "$(echo -en ${input})"
else
errorExit "Cant echo message: ${1}"
fi
fi
dbg "${FUNCNAME}() leaving function"
}
# Function to echo out a coloured bar between sections.
bar() {
if [ -z "${quietMode}" ]; then
echo -e "${blue}*-----------*${end}"
fi
}
# Function to echo out coloured stars between sections.
stars() {
if [ -z "${quietMode}" ]; then
echo -e "${boldRed}*************${end}"
fi
}
# Function to echo out "ok" after a check
ok() {
if [ -z "${quietMode}" ] || [ -n "${debug}" ]; then
${tprint}
echo -e "${green}[OK]${end}"
fi
}
# Function to echo out "Dryrun" after a check
dryRun() {
if [ -z "${quietMode}" ] || [ -n "${debug}" ]; then
${tprint}
echo -e "${yellow}[Dryrun]${end}"
fi
}
# Function to echo out "failed" after a check, and exit
failed() {
if [ -z "${quietMode}" ] || [ -n "${debug}" ]; then
${tprint}
echo -e "${warning}[FAILED]${end}"
fi
errorExit "${@}"
}
# Non Critical failed.
ncfailed() {
if [ -z "${quietMode}" ] || [ -n "${debug}" ]; then
${tprint}
echo -e "${warning}[FAILED]${end}"
fi
if [ -n "${1}" ]; then
foldIt "-e" "INFO: ${@}"
fi
}
# Reverse array. Take arguments in: "arrayname"
reverseArray() {
local -n array=${1:?Array name required}
local revarray="" e
for e in "${array[@]}"; do
revarray=("${e}" "${revarray[@]}")
done
array=(${revarray[@]})
}
# Debug function
dbg() {
if [ -n "${debug}" ]; then
local frame=0
local i=0
local functionStacktrace=()
local lineStacktrace=()
local debugMessage=""
while caller ${frame} >/dev/null; do
functionStacktrace[${frame}]=$(caller ${frame} | awk '{print $2}')
lineStacktrace[${frame}]=$(caller ${frame} | awk '{print $1}')
((frame++))
done
reverseArray "functionStacktrace"
reverseArray "lineStacktrace"
while [ ${#functionStacktrace[@]} -gt ${i} ]; do
debugMessage="${debugMessage}${functionStacktrace[${i}]}()line ${lineStacktrace[${i}]}: "
((i++))
done
debugMessage="${debugMessage}${*}"
logger -t ${0} "${debugMessage}"
echo "$(date +"${dateFormat}") ${0} ${debugMessage}" | tee -a ${debugLog}
fi
}
# Reports to web server
# Takes arguments in: var0=value0 var1=value1
report() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local i=0
local args=${#}
local awn=""
local doReport=""
if [ -n "${offline}" ]; then
dbg "\${offline} is set, don't report"
return 0
fi
if [ -n "${reportUrl}" ]; then
dbg "\${reportUrl} is set, try to reporting"
while [ ${args} -gt ${i} ]; do
awn="${awn}${1}&"
shift
((i++))
done
# TODO: Refactor to not use eval
doReport='wget "${reportUrl}" -q -O /dev/null --post-data "
date=$(date +"${dateFormat}")&
hostname=${HOSTNAME}&
user=${USER}&
get_envGitServer=${get_envGitServer}&
get_envGitUser=${get_envGitUser}&
get_envRepository=${get_envRepository}&
get_envBranch=${get_envBranch}&
gitServer=${gitServer}&
gitUser=${gitUser}&
repository=${repository}&
branch=${branch}&
quietMode=${quietMode}&
dryrun=${dryrun}&
debug=${debug}&
debugLog=${debugLog}&
noGet_envUpdate=${noGet_envUpdate}&
myName=${myName}&
localWorkDir=${localWorkDir}&
newFiles=${newFiles}&
updatedFiles=${updatedFiles}
createdDirs=${createdDirs}&
${awn}"'
foldIt "-n" "Reporting to web server"
if eval ${doReport}; then
ok
dbg "Reported to web server"
else
ncfailed
fi
else
dbg "\${reportUrl} is not set, don't reporting"
fi
dbg "${FUNCNAME}() leaving function"
}
# Function for exit due to fatal program error
# Takes argument as string containing error message
errorExit() {
dbg "${FUNCNAME}() was called, arg: ${*}"
echo -e "${warning}${myName}: ${1:-"Unknown Error"}${end}" 1>&2
dbg "${myName}: ${1:-"Unknown Error"}"
report "error=${1}"
cleanup
exit 1
dbg "${FUNCNAME}() leaving function"
}
# Help menu when invoked with -h
helpMenu() {
cat <<EOF
"Useage: ${0} arguments"
options:
-d Debug - shows whats happening and saves debugLog in the form
/tmp/${myName}.debugLog.2013-10-21T10:42:37.XXXXXXXXX
-f Offline - don't require internetconnection. Just refresh from localrepo.
-h This helptext
-l If debug is used, use this file as debugLog.
-n Dryrun - don't replace files, just show which files would be replaced.
May create local workdir for ${myName}.
-q Quietmode - no output exept errors, good for running from cron.
-r Directory to create and download repo to, default same name as my filename (${myName})
-u Do not update ${myName} even if newer is found
EOF
exit 0
}
# Function to download zip from github.
# Arg: server user repository branch filePath
downloadAndUnzip() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local server=${1}
local user=${2}
local repository=${3}
local branch=${4}
local inFile="https://${server}/${user}/${repository}/archive/${branch}.zip"
local outDir="${downloadDir}/${repository}"
local outFile="${repository}-${branch}.zip"
createDir -f -q ${downloadDir}/${repository}
foldIt "-n" "Downloading ${inFile}"
# Download
if [ -z "${debug}" ]; then
if wget ${inFile} -O ${outDir}/${outFile} -q; then
ok
dbg "Downloaded ${outFile}"
else
failed "Could not download zipfile"
fi
else
if wget ${inFile} -O ${outDir}/${outFile}; then
ok
dbg "Downloaded ${outFile}"
else
failed "Could not download zipfile"
fi
fi
foldIt "-n" "Unzipping ${outFile}"
# Unzip
if [ -z "${debug}" ]; then
if unzip -o -qq ${outDir}/${outFile} -d ${outDir}; then
ok
dbg "Unzipped file"
else
failed "Failed to unzip"
fi
else
if unzip -o ${outDir}/${outFile} -d ${outDir}; then
ok
dbg "Unzipped file"
else
failed "Failed to unzip"
fi
fi
foldIt "-n" "Moving files to ${localWorkDir}"
syncFiles "${outDir}/${repository}-${branch}" "${localWorkDir}/${repository}/"
dbg "${FUNCNAME}() leaving function"
}
# Function to clone and pull repository from gitserver.
# Arg: server user repository branch [ssh port (optional)]
gitCloneAndPull() {
dbg "${FUNCNAME}() was called, arg: ${*}"
depends git
local server=${1}
local user=${2}
local repository=${3}
local branch=${4}
local sshPort=${5:-"22"}
local gitRemoteRepo="ssh://${user}@${server}:${sshPort}/${pathToRepository}/${repository}"
createDir -q -f ${localWorkDir}/git
# Check if target directory exists.
if [ -d "${localWorkDir}/git/${repository}" ]; then
# Check if target is git repository.
if [ ! -d "${localWorkDir}/git/${repository}/.git" ]; then
errorExit "${localWorkDir}/git/${repository} is not an git repository."
fi
# Check that it is correct repository
cd ${localWorkDir}/git/${repository}
local checkedOutrepository=$(git remote -v | grep fetch | awk '{print $2}')
if ! echo ${checkedOutrepository} | grep -q "${repository}"; then
errorExit "Wrong repository: ${localWorkDir}/git/${repository}"
fi
# Save current branch
local startBranch=$(git branch --no-color | grep '\*' | awk '{print $2}')
foldIt "-n" "Git pull ${repository} to ${localWorkDir}/git/ "
if git pull -q; then
ok
dbg "Git pulled ${repository} to ${localWorkDir}/git/${repository}"
else
failed "Failed to git pull ${localWorkDir}/git/${repository}"
fi
else
# Local repository does not exists, trying to clone
cd ${localWorkDir}/git/
dbg "URL to use for git clone: ${gitRemoteRepo}"
foldIt "-n" "Git clone ${repository} to ${localWorkDir}/git/ "
if git clone -q ${gitRemoteRepo}; then
ok
dbg "Clone ${repository} to ${localWorkDir}/git/${repository}"
else
failed "Failed to clone ${repository} to ${localWorkDir}/git/${repository}"
fi
fi
cd ${localWorkDir}/git/${repository}
# Save current branch, if not set already
if [ -z "${startBranch}" ]; then
local startBranch=$(git branch --no-color | grep '\*' | awk '{print $2}')
fi
# Checkout correct branch
foldIt "-n" "Checkout branch ${branch}"
if git checkout ${branch} -q; then
ok
dbg "Checked out branch ${branch}"
else
failed "Could not checkout branch ${branch}"
fi
foldIt "-n" "Moving files to ${localWorkDir}"
createDir -f "${localWorkDir}/${repository}/${repository}-${branch}"
syncFiles "${localWorkDir}/git/${repository}/" "${localWorkDir}/${repository}/${repository}-${branch}"
# Restore staring branch
foldIt "-n" "Restoring original branch ${startBranch}"
if git checkout ${startBranch} -q; then
ok
dbg "Checked out branch ${startBranch}"
else
failed "Could not checkout branch ${startBranch}"
fi
cd ${myStartDirectory}
dbg "${FUNCNAME}() leaving function"
}
# Files that shall be copied
# Arg: dir_in_repo dir_to_be_moved_to _files_
copyFiles() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local fromDir=${1}
shift
local toDir=${1}
shift
local file=""
# Test if ${toDir} exists
createDir ${toDir}
for file in ${*}; do
# Test if the source file exists
if [ ! -f ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file} ]; then
foldIt "-n" "Checking for file ${file}"
failed "File does not exists: ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file}"
fi
# If the destination file exist ...
if [ -f "${toDir}/${file}" ]; then
# .. diff it with the source file
if ! diff -q ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file} ${toDir}/${file} >/dev/null 2>&1; then
if [ -z "${dryrun}" ]; then
# .. And if it is not the same, copy to backup file:
# TODO: gzip backup? Number of backups? Better structure?
createDir "${localWorkDir}/backup"
foldIt "-n" "Found difference in ${toDir}/${file}, making backup"
if [ $(echo ${file} | cut -c1) == "." ]; then
if cp ${toDir}/${file} ${localWorkDir}/backup/dot${file}."${ddate}"; then
ok
dbg "Backed up: ${localWorkDir}/backup/${file}.${ddate}"
else
ncfailed
fi
else
if cp ${toDir}/${file} ${localWorkDir}/backup/${file}."${ddate}"; then
ok
dbg "Backed up: ${localWorkDir}/backup/${file}.${ddate}"
else
ncfailed
fi
fi
fi
# .. Copy the new file
foldIt "-n" "Copy new ${toDir}/${file}"
if [ -n "${dryrun}" ]; then
dryRun
dryrunUpdatedFiles="${dryrunUpdatedFiles}${file} "
else
if cp ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file} ${toDir}/${file}; then
ok
dbg "Updated file: ${toDir}/${file} copied ok"
updatedFiles="${updatedFiles}${file} "
else
failed "Could not copy ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file} to ${toDir}/${file}"
fi
fi
else
dbg "${file} are up to date"
fi
# If the to_file dose not exist, just copy it.
else
foldIt "-n" "Copy new ${toDir}/${file}"
if [ -n "${dryrun}" ]; then
dryRun
dryrunNewFiles="${dryrunNewFiles}${file} "
else
if cp ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file} ${toDir}/${file} >/dev/null 2>&1; then
ok
dbg "New file: ${toDir}/${file} copied ok"
newFiles="${newFiles}${file} "
else
failed "Could not copy ${localWorkDir}/${repository}/${repository}-${branch}/${fromDir}/${file} to ${toDir}/${file}"
fi
fi
fi
done
dbg "${FUNCNAME}() leaving function"
}
# Number of variables that is supposed to be in confFile, is used to check if new confFile will be written
generateConfFile() {
dbg "${FUNCNAME}() was called, arg: ${*}"
confFileContent="\
# Where to download new get_env from (should be a github repository)
get_envGitServer=${get_envGitServer:-"github.com"}
# github user
get_envGitUser=${get_envGitUser:-"spetzreborn"}
# github repository
get_envRepository=${get_envRepository:-"get_env"}
# Branch from witch get_env is downloaded from. master or trunk
get_envBranch=${get_envBranch:-"master"}
# Where to download environment from.
gitServer=${gitServer:-"github.com"}
# git user
gitUser=${gitUser:-"spetzreborn"}
# git repository
repository=${repository:-"dotfiles"}
# Branch from witch environment is downloaded from. master or trunk
branch=${branch:-"master"}
# If not using github as repository you may need to set these settings:
# 'git clone ssh://gitUser@gitServer:sshPort/pathToRepository/repository'
sshPort=${sshPort:-"22"}
pathToRepository=${pathToRepository:-"none"}
# Path to local repository
localWorkDir=${localWorkDir}
# If set, report status to this address. (Uses report.php from github.com/spetzreborn/get_env)
reportUrl=\"\"
"
# TODO: Just grep on variables? Set and unset, eg reportUrl can be both.
confFileVariables=$(echo "${confFileContent}" | egrep -c '^[^#]')
dbg "${FUNCNAME}() leaving function"
}
# Change the values in ${confFile}
# Arg: variable value
changeConfFile() {
dbg "${FUNCNAME}() was called, arg: ${*}"
sed -i "s/\(${1} *= *\).*/\1${2}/" "${confFile}"
dbg "${FUNCNAME}() leaving function"
}
writeConfFile() {
dbg "${FUNCNAME}() was called, arg: ${*}"
# First time run - print GNU information
gnuLicense
local fileToWrite="${1}"
bar
foldIt "-n" "Saving default configuration in ${fileToWrite}"
if echo "${confFileContent}" >${fileToWrite}; then
ok
dbg "Wrote config to ${fileToWrite}"
else
failed "Could not write ${fileToWrite}"
fi
dbg "${FUNCNAME}() leaving function"
}
# Creates a directory
# Arg: Optional [-q|-f] /path/to/directory
# -q = quiet, don't show
# -f = force, create directory even if "dryrun" is invoked.
createDir() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local quiet=""
local force=""
local dir=""
while [ ${#} -gt 1 ]; do
case "${1}" in
-q)
dbg "Set quiet for createDir()"
quiet="yes"
shift
;;
-f)
dbg "Set force for createDir()"
force="yes"
shift
;;
esac
done
for dir in ${*}; do
dbg "Test if ${dir} exists"
if [ ! -d "${dir}" ]; then
if [ -z "${quiet}" ]; then
foldIt "-n" "Creating directory ${dir}"
fi
if [ -n "${dryrun}" ] && [ -z "${force}" ]; then
dbg "\${dryrun} set, don't create directory"
if [ -z "${quiet}" ]; then
dryRun
fi
dryrunCreatedDirs="${dryrunCreatedDirs}${dir} "
else
if mkdir -p ${dir}; then
dbg "Created ${dir}"
if [ -z "${quiet}" ]; then
ok
fi
createdDirs="${createdDirs}${dir} "
else
failed "Failed to create ${dir}"
fi
fi
else
dbg "Dir ${dir} already exists"
fi
done
dbg "${FUNCNAME}() leaving function"
}
# Echo variables to debug
showVariables() {
dbg "${FUNCNAME}() was called, arg: ${*}"
dbg "Variables I have: "
dbg "\${myName}: ${myName}"
dbg "\${localWorkDir}: ${localWorkDir:-""}"
dbg "\${get_envGitServer}: ${get_envGitServer:-""}"
dbg "\${get_envGitUser}: ${get_envGitUser:-""}"
dbg "\${get_envRepository}: ${get_envRepository:-""}"
dbg "\${get_envBranch}: ${get_envBranch:-""}"
dbg "\${gitServer}: ${gitServer:-""}"
dbg "\${gitUser}: ${gitUser:-""}"
dbg "\${repository}: ${repository:-""}"
dbg "\${branch}: ${branch:-""}"
dbg "\${debug}:${debug:-""}"
dbg "\${debugLog}: ${debugLog:-""}"
dbg "\${noGet_envUpdate}: ${noGet_envUpdate:-""}"
dbg "\${quietMode}: ${quietMode:-""}"
dbg "\${dryrun}:${dryrun:-""}"
dbg "\${offline}:${offline:-""}"
dbg "${FUNCNAME}() leaving function"
}
showVariablesHostConfig() {
dbg "${FUNCNAME}() was called, arg: ${*}"
dbg "Variables for ${1}:"
dbg "\${dirsToCreate}: ${dirsToCreate}"
# Call dbg() for all values in array ${files2copy}
local i=0
local array=""
for array in "${files2copy[@]}"; do
dbg "\${files2copy[${i}]}: ${array}"
((i++))
done
dbg "${FUNCNAME}() leaving function"
}
# Check that configuration files only have valid configurations.
# Arg: config-filetype [get_env|manifest] file
validateConfig() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local confType=${1}
local confFile=${2}
local badContent=""
local validateString=""
dbg "confType = ${confType}"
case "${confType}" in
"get_env")
dbg "Validate type: get_env"
badContent=$(egrep -v \
-e "^#" \
-e "^$" \
-e "^get_envGitServer=[A-Za-z0-9/_~. \"-]+$" \
-e "^get_envGitUser=[A-Za-z0-9/_~. \"-]+$" \
-e "^get_envRepository=[A-Za-z0-9/_~. \"]+$" \
-e "^get_envBranch=[A-Za-z0-9/_~. \"]+$" \
-e "^get_envBranch=[A-Za-z0-9/_~. \"]+$" \
-e "^gitServer=[A-Za-z0-9/_~. \"-]+$" \
-e "^gitUser=[A-Za-z0-9/_~. \"-]+$" \
-e "^repository=[A-Za-z0-9/_~. \"]+$" \
-e "^branch=[A-Za-z0-9/_~. \"]+$" \
-e "^sshPort=([A-Za-z0-9/_~. \"]+)?$" \
-e "^pathToRepository=([A-Za-z0-9/_~. \"]+)?$" \
-e "^localWorkDir=[A-Za-z0-9/_~. \"]+$" \
-e "^reportUrl=[A-Za-z0-9/_~. :\"]*$" \
"${confFile}")
;;
"manifest")
dbg "Validate type: manifest"
badContent=$(egrep -v \
-e "^#" \
-e "^$" \
-e "dirsToCreate=" \
-e "^files2copy[[][0-9]+[]]='?\"?[A-Za-z0-9/_~. $]+'?\"?" \
-e "ignoreHosts=" \
"${confFile}")
;;
*)
dbg "${confType} is not an valid confType."
errorExit "Internal error. Run with -d to get more information."
;;
esac
if [ -n "${badContent}" ]; then
dbg "${confFile} is not sanitized: ${badContent}"
errorExit "${confFile} contains bad things: ${badContent}"
else
dbg "${confFile} is sanitized, no bad content"
fi
dbg "${FUNCNAME}() leaving function"
}
# Test if there was a change in get_env - and is needed to be run again.
# Need absolute name in from file, so it truly can make variable name.
# This diff dose not care about comments.
get_envDiffAndRestart() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local get_envDownloaded="${localWorkDir}/${get_envRepository}/${get_envRepository}-${get_envBranch}/${myAbsoluteName}"
if ! diff -q -I '^# .*' ~/${myName} ${get_envDownloaded} >/dev/null 2>&1; then
foldIt "-e" "${info}Found newer ${myName}${end}"
if [ -n "${noGet_envUpdate}" ] || [ -n "${dryrun}" ]; then
dbg "${noGet_envUpdate} ${dryrun} is set, don't replace or run newer"
foldIt "Do not run newer ${myName}, ${noGet_envUpdate} ${dryrun} is invoked."
else
foldIt "-en" "Replacing $(echo ~)/${myName}"
if cp ${get_envDownloaded} ~/${myName}; then
ok
dbg "Replaced ${myName} with newer successfully."
else
failed "Could not copy the file ${myAbsoluteName} to ${myName}"
fi
foldIt "-e" "${info}Executing new $(echo ~)/${myName}${end}"
bar
foldIt ""
foldIt ""
stars
foldIt ""
foldIt ""
# Makes next script start with debug if this instance was started with debug.
if [ -n "${debug}" ]; then
cleanup
exec ~/${myName} -r "${localWorkDir}" "${quietMode}" "${noGet_envUpdate}" "${debug}" -l "${debugLog}"
else
cleanup
exec ~/${myName} -r "${localWorkDir}" "${quietMode}" "${noGet_envUpdate}"
fi
fi
else
foldIt "Already running latest ${myName}"
fi
dbg "${FUNCNAME}() leaving function"
}
# Wrapper function for syncing files.
# Arg: sourceDir destDir
syncFiles() {
dbg "${FUNCNAME}() was called, arg: ${*}"
local sourceDir=${1}
local destDir=${2}
if [ ! -e "${sourceDir}" ]; then
errorExit "${sourceDir} does not exists."
fi
if [ -z "${debug}" ]; then
if rsync -aq --delete ${sourceDir} ${destDir}; then
ok
dbg "rsync to ${destDir}"
else
failed "Failed to rsync"
fi
else
if rsync -av --delete ${sourceDir} ${destDir}; then
ok
dbg "rsync to ${destDir}"
else
failed "Failed to sync"
fi
fi
dbg "${FUNCNAME}() leaving function"
}
# TODO: Call cleanup() by trap? trap cleanup EXIT
cleanup() {
# Remove downloaded files and temporary directories
dbg "${FUNCNAME}() was called, arg: ${*}"
if [ -d ${downloadDir} ]; then
rm -r ${downloadDir}
fi
dbg "${FUNCNAME}() leaving function"
}
### End of functions
# Make tput work in screen
if [ "${TERM}" = "screen" ]; then
TERM=xterm
dbg "\${TERM} was screen, setting it to xterm for running in this script"
fi
while getopts ":dfhl:nqr:u" opt; do
case ${opt} in
d)
debug="-d"
echo "Debug is set, saving debugLog to: ${debugLog}"
;;
f)
offline="true"
;;
h)
helpMenu
;;
l)
debugLog=$(readlink -f ${OPTARG})
;;
n)
dryrun="-n"
;;
q)
quietMode="-q"
;;
r)
localWorkDir=$(readlink -f ${OPTARG})
;;
u)
noGet_envUpdate="-u"
;;
\?)
errorExit "Invalid option: -${OPTARG}"
;;
:)
errorExit "Option -${OPTARG} requires an argument."
;;
esac
done
# Only create a debugLog if there is not one.
if [ -n "${debug}" ]; then
if [ -z "${debugLog}" ]; then
debugLog=$(mktemp /tmp/${myName}.debugLog."${ddate}".XXXXXX)
fi
fi
dbg "I have started, read variables and functions and are on line:${LINENO}"
showVariables
# Verify write permissions in home directory
if [ ! -w ~ ]; then
errorExit "Have no write permissions in $(echo ~)"
fi
# If argument -r was not given, set default ${localWorkDir} to absolute path
if [ -z "${localWorkDir:-""}" ]; then
localWorkDir="$(echo ~/.${myName})"
dbg 'Setting defult ${localWorkDir} to absolute path: ' "${localWorkDir}"
fi
# generateConfFile() must be run before attempting to compare confFiles, but after ${localWorkDir} is set.
generateConfFile
# Checks if confFile exists and have read and write permissions.
if [ -f "${confFile}" ]; then
if [ ! -w "${confFile}" ] || [ ! -r "${confFile}" ]; then
errorExit "No read or write permissions for ${confFile}"
fi
# Sanitize confFile so that only sane line exists.
validateConfig "get_env" "${confFile}"
# Matches variables in default confFile and confFile. Only counts VARIABLE_NAME=variable. Variables must be set
#TODO: Don't invert check, just make regex for variables.
numberOfVariablesInConfFile=$(egrep -c -e "^[^#]" "${confFile}")
if [ "${numberOfVariablesInConfFile}" -eq "${confFileVariables}" ]; then
dbg "confFile contains correct number of variables."
else
dbg "Wrong number of variable in ${confFile}, ${numberOfVariablesInConfFile} vs ${confFileVariables}"
dbg "Create new conffile"
# Create new confFile
writeConfFile ${confFile}.new
errorExit "Created ${confFile}.new, before running ${myName} again, edit and move this file to ${confFile}"
fi
else
dbg "\${confFile} (${confFile}) does not exist, creating."
writeConfFile "${confFile}"
errorExit "Created ${confFile}, before running ${myName} again, edit ${confFile}"
fi
# Source confFile.
foldIt "-n" "Loading configuration in ${confFile}"
if . "${confFile}"; then
ok
dbg "Sourced confFile: ${confFile}"
else
failed "Could not source confFile: ${confFile}"
fi
# Git may clone both with and without trailing '.git'. Local repository will not have .git,
# therefore removing it from variable
if echo ${repository} | grep -q '\.git$'; then
dbg "\${repository} \"${repository}\" ends in \".git\". Removing trailing .git"
repository=$(echo ${repository} | sed 's/\.git$//')
fi
showVariables
# Some verbose things
foldIt "Using ${localWorkDir} as working directory."
foldIt "Using branch: ${get_envBranch} "
# Check for internet connection
if [ -n "${offline}" ]; then
dbg "\${offline} is set \"${offline}\", don't check internet connection"
else
dbg "Checking for internet connection . . ."
inetCon=$(host "${get_envGitServer}")
inetErr=${?}
dbg "Checked internet connection by 'host ${get_envGitServer}' answer:${inetCon}"
if [ "${inetErr}" != "0" ]; then
offline="Don't try to report, no connection"
errorExit "No internet connection or none functional dns. Exiting"
fi
fi