#!/bin/bash

# according to /usr/include/sysexit.h
EXIT_USAGE_ERROR=64

lampp_bin=/opt/lampp/bin
database_dump=database_dump
tcroot=/home/tc

exit_with_usage() {
    echo "tc-ar package     <destination>"
    echo "      restore     <backup dir>"
    echo "      list remote <ip>"
    echo "      list local  <path>"
    echo "      push remote <src> <ip>   <stat_file>"
    echo "      push local  <src> <dest> <stat_file>"
    echo "      stat <stat_file>"
    echo "      ping <ip>"
    exit $EXIT_USAGE_ERROR
}

print_exit_value() {
    res="SUCCESS"
    if [ $1 -ne 0 ]; then
        res="FAILURE"
    fi
    echo "[$res] $2, $1"
    return $1
}

if [ $# -lt 1 ]; then
    exit_with_usage
fi

sub1=$1

current_date=$(printf '%(%Y%m%d_%H%M%S)T\n' -1)

if [ $sub1 == "package" ]; then
    # package configuration files from whole system, like /etc.
    # then, export database into the SQL file
    # MySQL maybe use replication instead of export/import
    # 
    backup_dir="$tcroot/opt/backup"
    mkdir -p "$backup_dir"
    echo "prepare backup directory, $backup_dir"
    db_file="$backup_dir/db-$current_date.export"
    echo "backup database to $db_file"
    ppp=$(grep TC_DB_PASS /opt/lampp/etc/site-tc.https.conf | awk '{print $3}')
    $lampp_bin/mysqldump -p$ppp -u tcweb --databases tc > "$db_file"
    exit_val=$?
    cp --remove-destination "$db_file" "$backup_dir/db.export"
    # clean up old db dump files before 14 days
    find $backup_dir -name db-*.export -mtime 14 -delete
    echo "backup configuration files"
    cp -vf /etc/dnsmasq.more.conf "$backup_dir/dnsmasq.more.conf"
    cp -vf /etc/dnsmasq-tftp.conf "$backup_dir/dnsmasq-tftp.conf"
    cp -vf /etc/dnsmasq-notftp.conf "$backup_dir/dnsmasq-notftp.conf"
    cp -vf /etc/ethers "$backup_dir/ethers"
    cp -vf /home/tc/etc/tc.ini "$backup_dir/tc.ini"
    print_exit_value $exit_val "backup TC database and configuration"
    exit $exit_val

elif [ $sub1 == "restore" ]; then
    lair=$2
    # check if the lair is good
    if [ ! -d "$lair/opt" ] || [ ! -d "$lair/etc" ] ; then
        print_exit_value 1 "invalid dir for restore, $lair"
        exit 1
    fi

    # error if /home/tc does not existed
    if [ ! -d "$tcroot" ]; then
        print_exit_value 1 "Cannot find TC installation in /home/tc"
    fi

    # keep nic/ipv4 before renaming /home/tc
    nic=$($tcroot/bin/network nic)
    ipv4=$($tcroot/bin/network ip)

    echo "move existed home to /home/tc-$current_date"
    mv --no-target-directory --force "$tcroot" "/home/tc-$current_date"

    echo "restore tc home from $lair"
    mv --no-target-directory --force --verbose "$lair" "$tcroot"
    db_file="$tcroot/opt/backup/db.export"
    echo "restore database from $db_file"
    $lampp_bin/mysql -p -u root < "$db_file"

    # create not synced folders
    cp -a "/home/tc-$current_date/var" "$tcroot/var"
    cp -a "/home/tc-$current_date/bin" "$tcroot/bin"

    # replace with new files and restore settings kept
    echo "restore configuration files"
    cp -vf "$tcroot/opt/backup/dnsmasq.more.conf" /etc/dnsmasq.more.conf
    cp -vf "$tcroot/opt/backup/dnsmasq-tftp.conf" /etc/dnsmasq-tftp.conf
    cp -vf "$tcroot/opt/backup/dnsmasq-notftp.conf" /etc/dnsmasq-notftp.conf
    cp -vf "$tcroot/opt/backup/ethers" /etc/ethers
    cp -vf "$tcroot/opt/backup/tc.ini" /home/tc/etc/tc.ini

    # restore ipv4 to use previous address
    sed -i "/option=6/c dhcp-option=6,$ipv4" "/etc/dnsmasq.more.conf"

    # restart tacker to load new seeds
    $tcroot/bin/tc-delivery-server restart
    echo "*******************************************"
    echo ""
    echo "  RESTART TO FINISH THIS IMPORT OPERATION  "
    echo ""
    echo "*******************************************"
    exit 0
# 
# List backup files for both of local and remote
# 
elif [ $sub1 == "list" ]; then
    exc="$tcroot/etc/backup_excluded"
    if [ $# -eq 4 ]; then
        src=$3
        dest=$4
        opt="--archive --update --delete --list-only --exclude-from=$exc"
        if [ $2 == "local" ]; then
            rsync $opt "$src" "$dest"
        else
            # using SSH tunnel
            # 
            rsync $opt --timeout=20 "$src" "root@${dest}:/home/tcharbor/tc"

            #  
            # using rsync daemon
            # 
            # rsync_pwd=/etc/rsync.passwd
            # rsync $opt --timeout=20 --password-file="$rsync_pwd" "$src" tc@$dest::backup
        fi
        ret=$?
        print_exit_value $ret "list backup content for $4"
    else
        exit_with_usage
    fi

elif [ $sub1 == "stat" ]; then
    awk 'BEGIN{RS="\r";} END{print}' $2
    exit $?

elif [ $sub1 == "ping" ]; then
    # using SSH tunnel
    # 
    ssh -oBatchMode=yes root@$2 who
    ret=$?
    print_exit_value $ret "try SSH login on host $2"
    exit $ret

    #  
    # using rsync daemon
    # 
    # rsync --dry-run $2::
    # ret=$?
    # print_exit_value $ret "dry run on host $2"
    # exit $ret
#
# Push backup files to the destination
#
elif [ $sub1 == "push" ]; then
    exc="$tcroot/etc/backup_excluded"
    opt_local="--sparse --archive --info=progress2 --exclude-from=$exc"
    #  
    # using SSH tunnel
    # 
    opt_remote="$opt_local --timeout=20"
    #  
    # using rsync daemon
    # 
    # opt_remote="$opt_local --no-g --timeout=20 --password-file=$rsync_pwd"
 
    if [ $# -eq 4 ]; then
        src=$3
        dest=$4
        if [ $2 == "local" ]; then
            rsync $opt_local $src $dest
        else
            #  
            # using SSH tunnel
            # 
            rsync $opt_remote "$src" "root@${dest}"
            #  
            # using rsync daemon
            # 
            # rsync $opt_remote $src "tc@$dest::backup"
        fi
        exit $?

    elif [ $# -eq 5 ]; then
        src=$3
        dest=$4
        stat=$5
        if [ $2 == "local" ]; then
            echo "push to local directory $dest"
            rsync $opt_local $src $dest > "$stat"
        else
            echo "push to remote host $dest over SSH tunnel"
            rsync $opt_remote $src "root@${dest}" > "$stat"
        fi
#        pid_file="$tcroot/var/tc-ar.pid"
#        echo $! > $pid_file
#        wait $!
        exit_val=$?
#        rm -f $pid_file
        print_exit_value $exit_val "backup to $dest"
        touch "$tcroot/var/ar.lastrun"
        exit $exit_val

    else
        exit_with_usage
    fi
fi
