#!/bin/bash

cd ${0%${0##*/}}.

# apps used
GZIP=gzip
TAR=tar
MYSQL=mysql
MYSQLDUMP=mysqldump

# parse database access from data.properties
file="data/data.properties"

while IFS="=" read -r key value; do
    case "$key" in
        "db.url") 
    	    if [[ "${value}" =~ ([[:alpha:][:digit:]_\.\-]+):*([[:digit:]]*)/([[:alpha:][:digit:]_\.\-]+) ]]
    	    then
    		HOST_SQL=${BASH_REMATCH[1]}
    		PORT_SQL=${BASH_REMATCH[2]}
    		DBASE_NAME=${BASH_REMATCH[3]}
    	    fi        
        ;;
        "db.user") 
    	    USER_SQL="$value" 
    	;;
    	"db.pswd") 
    	    PASSWORD_SQL="$value"
    	;;
    esac
done < "$file"

if [ -n "$PORT_SQL" ];
then
    PORT_SQL=" -P $PORT_SQL"
fi

######## modify on your own risk ###########
TMP=snptmp
SNAPSHOTS_DIR=snapshots
TMP_IM=installed_modules.sql
LIB_APP=lib/app
CLIENT_JARS=client.jars
WEBROOT=webroot

# exit from script on any error
set -e

function create 
{
    if [ ! -d ${SNAPSHOTS_DIR} ];
    then
	mkdir ${SNAPSHOTS_DIR}
    fi

    rm -rf ${TMP}
    mkdir ${TMP}

    cd ${TMP}
    ${MYSQLDUMP} --host=${HOST_SQL} --user=${USER_SQL} --password=${PASSWORD_SQL} ${PORT_SQL} ${DBASE_NAME} installed_modules > ${TMP_IM}

    mkdir -p ${LIB_APP}
    cp  ../${LIB_APP}/* ./${LIB_APP}
    mkdir -p ../${CLIENT_JARS}
    cp -r ../${CLIENT_JARS} ./
    cp -r ../${WEBROOT} .

    CUR_DATE=`date +%Y.%m.%d_%H.%M.%S`
    CUR_SNAPSHOT_NAME=${CUR_DATE}.tar

    echo "Snapshot name: $CUR_SNAPSHOT_NAME"

    ${TAR} -cf ${CUR_SNAPSHOT_NAME} ${TMP_IM} ${LIB_APP} ${CLIENT_JARS} ${WEBROOT}

    cd ..
    ${GZIP} -cf ${TMP}/${CUR_SNAPSHOT_NAME} > ${SNAPSHOTS_DIR}/${CUR_SNAPSHOT_NAME}.gz

    rm -rf ${TMP}
}

function restore 
{
    rm -rf ${TMP}

    mkdir ${TMP}
    cd ${TMP}

    ${TAR} -xzf ../${SNAPSHOTS_DIR}/$1

    rm -rf ../${LIB_APP}
    cp -r ${LIB_APP} ../${LIB_APP}
    rm -rf ../${CLIENT_JARS}
    cp -r ${CLIENT_JARS} ../${CLIENT_JARS}
    rm -rf ../${WEBROOT}
    cp -r ${WEBROOT} ../.

    ${MYSQL} -B --host=${HOST_SQL} --user=${USER_SQL} --password=${PASSWORD_SQL} ${PORT_SQL} ${DBASE_NAME} < ${TMP_IM}
	
    cd ..
    rm -rf ${TMP}
}

function help 
{
    echo "USAGE: ./snapshot.sh [CMD]"
    echo "Where [CMD] in:"
    echo " * create - to create snapshot in 'snapshots' directory"
    echo " * restore [FILE] - to restore state to [FILE]'s snapshot state"
    exit 1
}

if [ -z $1 ]
then
    help
fi

if [ "$1" = "create" ]
then
    create
else
    if [ "$1" = "restore" ]
    then
	if [ -z $2 ]
	then
	    echo "no backup file given"
	    echo
	    help
	else
	    restore $2
	fi
    else
	echo "unknown command '$1'"
	echo
	help
    fi
fi

exit 0