Rev Author Line No. Line
3407 kakl 1 #!/usr/bin/env bash
2  
3 [[ $# -ne 1 ]] && echo "Usage: ./sync.sh /path/to/folder" && exit 1
4  
5 # Redirect stdout ( > ) into a named pipe ( >() ) running "tee"
6 exec > >(tee "$1"/logfile.txt)
7  
8 # Also redirect stderr
9 exec 2>&1
10  
3410 kakl 11 FREQUENCY=180
3407 kakl 12  
13 TIDYUP="$(pwd)/tidyup.sh"
14 RSYNC="$(pwd)/upload.sh"
15  
16 DEFAULT="\033[00m"
17 RED="\033[01;31m"
18 BLUE="\033[01;36m"
19  
20 function info() {
21 echo -en "$BLUE"; echo -n $1; echo -e "$DEFAULT"
22 }
23 function error() {
24 echo -en "$RED"; echo -n $1; echo -e "$DEFAULT"
25 }
26  
27 function syncdir() {
28 EXIT=1
29 i=1
3410 kakl 30 # while [ $EXIT -ne 0 ]; do
3415 kakl 31 info "Trying to sync $1, $2"
32 "$RSYNC" $1 $2
3407 kakl 33 EXIT=$?
34 [ $EXIT -ne 0 ] && error "sync failed"
35 let i++
3410 kakl 36 # done
3407 kakl 37 return $EXIT
38 }
39  
40 # Sort files
41 # Mask
42 function tidyup() {
43 info "sorting $1"
44 "$TIDYUP" $1
45 if [ "$?" -ne 0 ]; then
46 error "sorting failed, please send logfile.txt to toxygen1@gmail.com"
47 return 1
48 fi
49 return 0
50 }
51  
52 # Test public key authentication
53 function sshtest() {
54 ./test.sh
55 if [ "$?" -eq 0 ]; then
56 info "Authentication works"
57 return 0
58 else
59 error "Authentication does not work"
60 return 1
61 fi
62 }
63  
64 # Check if we can connect, otherwise terminate
65 sshtest || exit 1
66  
67 # Change working directory
68 cd $1
69  
3410 kakl 70  
3407 kakl 71 # reset counter
72 HOURCOUNT=24
73  
74 # Periodically tidy up and do incremental sync
75 while :
76 do
77 # start timer
78 start_time=`date +%s`
79  
80 # sort
81 tidyup $1 || error "Sort failed, please send logfile.txt to toxygen1@gmail.com"
82  
83 # increase counter every hour
84 # if 24 hour mark is hit, do daily sync
85 if [[ "$HOURCOUNT" -eq 24 ]]
86 then
87 info "Doing complete sync"
88 syncdir .
89 HOURCOUNT=0
90 fi
91  
92 if [ -f "$1"/LAST ]
93 then
94 # next line is important for the first run of the loop
95 read LAST < "$1"/LAST
96  
97 let HOURCOUNT++
98  
99 # read last processed day
100 OLD="$LAST"
101 read LAST < "$1"/LAST
102  
103 # sync last updated folders
3415 kakl 104 syncdir ./audio/"$LAST"
105 syncdir ./capture/"$LAST"
106 syncdir ./data/"$LAST"
107 syncdir ./data --delete
3407 kakl 108  
109 # days changed, sync yesterday too
110 [[ "$LAST" != "$OLD" ]] && info "syncing yesterday" && syncdir "$OLD"
111  
112 tail -n 1000 "$1"/logfile.txt > "$1"/tmp.txt
113 mv "$1"/tmp.txt "$1"/logfile.txt
114 fi
115  
116 # end timer
117 end_time=`date +%s`
118 ELAPSED=`expr $end_time - $start_time`
119 info "execution time was $ELAPSED s"
3410 kakl 120  
121 date
122  
3407 kakl 123 # if last sync took less than TIME, sleep to make up 1 hour
3410 kakl 124 # [[ $ELAPSED -lt $FREQUENCY ]] && sleep `expr $FREQUENCY - $ELAPSED`
125 sleep $FREQUENCY
3407 kakl 126 done