Rev Author Line No. Line
2729 toxygen 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 logfile.txt)
7  
8 # Also redirect stderr
9 exec 2>&1
10  
11 FREQUENCY=60
12  
13 TIDYUP="./tidyup.sh"
14 RSYNC="./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  
24 function error() {
25 echo -en "$RED"; echo -n $1; echo -e "$DEFAULT"
26 }
27  
28 function syncdir() {
29 EXIT=1
30 i=1
31 while [ $EXIT -ne 0 ]; do
32 info "Trying to sync $1, try number $i"
33 "$RSYNC" "$1"
34 EXIT=$?
35 [ $EXIT -ne 0 ] && error "sync failed"
36 let i++
37 done
38 return $EXIT
39 }
40  
41 function tidyup() {
42 info "sorting $1"
43 "$TIDYUP" $1
44 EXIT=$?
45 if [ $EXIT -eq 1 ]; then
46 info "No new files to sort"
47 return 0
48 elif [ $EXIT -ne 0 ]; then
49 error "sorting failed, please send logfile.txt to toxygen1@gmail.com"
50 return 1
51 fi
52 return 0
53 }
54  
55 # Change working directory
56 cd $1
57  
58 # reset counter
59 HOURCOUNT=24
60  
61 # Periodically tidy up and do incremental sync
62 while :
63 do
64 # start timer
65 start_time=`date +%s`
66  
67 # sort
68 tidyup . || error "Sort failed, please send logfile.txt to toxygen1@gmail.com"
69  
70 # increase counter every hour
71 # if 24 hour mark is hit, do daily sync
72 if [[ "$HOURCOUNT" -eq 24 ]]
73 then
74 info "Doing complete sync"
75 syncdir .
76 HOURCOUNT=0
77 # next line is important for the first run of the loop
78 read LAST < LAST
79 fi
80 let HOURCOUNT++
81  
82 # read last processed day
83 OLD="$LAST"
84 read LAST < LAST
85  
86 # sync last updated folder
87 syncdir "$LAST"
88  
89 # days changed, sync yesterday too
90 [[ "$LAST" != "$OLD" ]] && info "syncing yesterday" && syncdir "$OLD"
91  
92 tail -n 1000 logfile.txt > tmp.txt
93 mv tmp.txt logfile.txt
94  
95 # end timer
96 end_time=`date +%s`
97 ELAPSED=`expr $end_time - $start_time`
98 info "execution time was $ELAPSED s"
99  
100 # if last sync took less than TIME, sleep to make up 1 hour
101 [[ $ELAPSED -lt $FREQUENCY ]] && sleep `expr $FREQUENCY - $ELAPSED`
102 done