#!/usr/bin/env bash

SERVER="root@121.40.151.55"

LOCAL="/data/www/webmail/"
REMOTE="/backup/"

LOCAL_TSFILE="/data/www/.backup_timestamp"
REMOTE_TSFILE="/root/.backup_timestamp"

function confirm() {
	echo -n "$1"
	read answer
	if [[ $answer != 'y' ]]; then
		echo 'exit'
		exit 0
	fi
}

function backup() {
	rsync -n -av --delete $LOCAL ${SERVER}:${REMOTE}
	confirm "确定需要备份文件吗？[Y/N]"
	rsync -av --delete $LOCAL ${SERVER}:${REMOTE}
	ts_local=$( date +%Y%m%d%H%M%S )
	echo -n $ts_local > $LOCAL_TSFILE
	ssh $SERVER "echo -n $ts_local > REMOTE_TSFILE"
}

function download() {
	rsync -n -av --delete ${SERVER}:${REMOTE} $LOCAL 
	confirm "确定要下载文件吗？[Y/N]"
	rsync -av --delete ${SERVER}:${REMOTE} $LOCAL 
	ts_local=$( date +%Y%m%d%H%M%S )
	echo -n $ts_local > $LOCAL_TSFILE
}

ts_remote=$( ssh $SERVER "cat $REMOTE_TSFILE" )
ts_local=$( cat $LOCAL_TSFILE )

echo "远程文件的时间戳: $ts_remote"
echo "本地文件的时间戳: $ts_local"

if [[ $1 == 'backup' ]]; then
	echo "文件备份中"
	backup	
	exit 0
fi

if [[ $1 == 'download' ]]; then
	echo "文件下载中"
	download	
	exit 0
fi

if [[ $ts_local -ge $ts_remote ]]; then
	echo "本地文件更新"
	backup
	exit 0
fi

if [[ $ts_local -lt $ts_remote ]]; then
	echo "远程文件已更新"
	download
	exit 0
fi
