#!/bin/sh
###################################################################
#  Web Backup version 1.0.3 Author: Jager <ge@zhangge.net>        #
# For more information please visit https://zhangge.net/5111.html #
#-----------------------------------------------------------------#
#  Copyright ©2016 zhangge.net. All rights reserved.              #
###################################################################

test -f /etc/profile && . /etc/profile >/dev/null 2>&1
baseDir=$(cd $(dirname $0) && pwd)
zip --version >/dev/null || yum install -y zip
ZIP=$(which zip)
TODAY=`date +%u`
PYTHON=$(which python)
MYSQLDUMP=$(which mysqldump)

# 新增的OSS上传文件函数,请按照实际情况修改参数！
uploadToOSS()
{
    $PYTHON $baseDir/oss.upload.py 认证KEY 认证密钥 oss-cn-qingdao-internal.aliyuncs.com Bucket名称 $1
}

printHelp()
{
clear
printf '
=====================================Help infomation=========================================
1. Use For Backup database:
The $1 must be [db]
    $2: [domain]
    $3: [dbname]
    $4: [mysqluser]
    $5: [mysqlpassword]
    $6: [back_path]

For example:./backup.sh db zhangge.net zhangge_db zhangge 123456 /home/wwwbackup/zhangge.net

2. Use For Backup webfile:
The $1 must be [\file]:
    $2: [domain]
    $3: [site_path]
    $4: [back_path]

For example:./backup.sh file zhangge.net /home/wwwroot/zhangge.net /home/wwwbackup/zhangge.net
=====================================End of Hlep==============================================

'
exit 0
}

backupDB()
{
    domain=$1
    dbname=$2
    mysqluser=$3
    mysqlpd=$4
    back_path=$5
    test -d $back_path || (mkdir -p $back_path || echo "$back_path not found! Please CheckOut Or feedback to zhangge.net..." && exit 2)
    cd $back_path
    $MYSQLDUMP -u$mysqluser -p$mysqlpd $dbname --skip-lock-tables --default-character-set=binary >$back_path/$domain\_db_$TODAY\.sql
    test -f $back_path/$domain\_db_$TODAY\.sql || (echo "MysqlDump failed! Please CheckOut Or feedback to zhangge.net..." && exit 2)
    $ZIP -Pmypassword -m $back_path/$domain\_db_$TODAY\.zip $domain\_db_$TODAY\.sql && \
    uploadToOSS $back_path/$domain\_db_$TODAY\.zip
}

backupFile()
{
    domain=$1
    site_path=$2
    back_path=$3
    test -d $site_path || (echo "$site_path not found! Please CheckOut Or feedback to zhangge.net..." && exit 2)
    test -d $back_path || (mkdir -p $back_path || echo "$back_path not found! Please CheckOut Or feedback to zhangge.net..." && exit 2)
    test -f $back_path/$domain\_$TODAY\.zip && rm -f $back_path/$domain\_$TODAY\.zip
    $ZIP -Pmypassword -9r $back_path/$domain\_$TODAY\.zip $site_path && \
    uploadToOSS $back_path/$domain\_$TODAY\.zip    
}

while [ $1 ]; do
    case $1 in
        '--db' | 'db' )
        backupDB $2 $3 $4 $5 $6
        exit
        ;;
        '--file' | 'file' )
        backupFile $2 $3 $4
        exit  
        ;;
        * )
        printHelp
        exit
        ;;
    esac
done
printHelp