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  
2730 toxygen 41 # Sort files
42 # Mask
2729 toxygen 43 function tidyup() {
44 info "sorting $1"
45 "$TIDYUP" $1
2730 toxygen 46 if [ "$?" -ne 0 ]; then
2729 toxygen 47 error "sorting failed, please send logfile.txt to toxygen1@gmail.com"
48 return 1
49 fi
50 return 0
51 }
52  
2730 toxygen 53 # Test public key authentication
54 function sshtest() {
55 ./test.sh
56 if [ "$?" -eq 0 ]; then
57 info "Authentication works"
58 return 0
59 else
60 error "Authentication does not work"
61 return 1
62 fi
63 }
64  
65 # Check if we can connect, otherwise terminate
66 sshtest || exit 1
67  
2729 toxygen 68 # Change working directory
69 cd $1
70  
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 . || 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 # next line is important for the first run of the loop
91 read LAST < LAST
92 fi
93 let HOURCOUNT++
94  
95 # read last processed day
96 OLD="$LAST"
97 read LAST < LAST
98  
99 # sync last updated folder
100 syncdir "$LAST"
101  
102 # days changed, sync yesterday too
103 [[ "$LAST" != "$OLD" ]] && info "syncing yesterday" && syncdir "$OLD"
104  
105 tail -n 1000 logfile.txt > tmp.txt
106 mv tmp.txt logfile.txt
107  
108 # end timer
109 end_time=`date +%s`
110 ELAPSED=`expr $end_time - $start_time`
111 info "execution time was $ELAPSED s"
112  
113 # if last sync took less than TIME, sleep to make up 1 hour
114 [[ $ELAPSED -lt $FREQUENCY ]] && sleep `expr $FREQUENCY - $ELAPSED`
115 done