#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

abort() {
    echo >&2 '
###############
### ABORTED ###
###############
    '
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

enforce_root

OS="`getos`"

BACKUP_FILE=""
BACKUP_TYPE=""

echo_help() {
	echo "restore-db [-h] [-f]
	-h | --help show help
	-f | --file tarball for database restoration (should be a .tar or .cus)
	"
}

while getopts ":hf:" option; do
	case $option in 
		h) # display help
			echo_help
			exit;;
		f) # path to config tar to apply
			BACKUP_FILE=$OPTARG;;
		/?) # invalid option
			echo "Invalid option"
			echo_help
			exit;;
	esac
done


case $BACKUP_FILE in
    *.tar)  BACKUP_TYPE="-t";;
    *.cus)  BACKUP_TYPE="-c";;
    *)      echo "Invalid backup extension needs to be .cus or .tar"
            exit;;
esac


restore_ubuntu () {
        echo "#### restarting postgresql"
        service postgresql restart
        echo "#### dropping dosis2 database"
        dropdb -U dsuper dosis2
        echo "#### recreating dosis2 database"
        /usr/bin/createdb -U dsuper -O dsuper dosis2
        echo "#### restoring dosis2 database"
        if [ "${BACKUP_TYPE}" = "-t" ]; then
            /usr/bin/pg_restore -Ft -U dsuper -d dosis2 $BACKUP_FILE
        elif [ "${BACKUP_TYPE}" = "-c" ]; then
            /usr/bin/pg_restore -Fc -U dsuper -d dosis2 $BACKUP_FILE
        else
            echo "Invalid backup extension, needs to be .cus or .tar"
        fi
}


if [ "`prompt_yes_no 'WARNING: This will drop the current dosis2 database and restore it using the backup you provided. Continue?'`" = "yes" ]; then
    echo "#### restoring backup for Ubuntu type"
    restore_ubuntu
fi

trap : 0

echo >&2 '
############
### DONE ###
############
'

