#!/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-labels [-h] [-f]
	-h | --help show help
	-f | --file tarball for database labels 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 "#### restoring dosis2 labels"
        if [ "${BACKUP_TYPE}" = "-t" ]; then
            /usr/bin/pg_restore -U dsuper -F t -v -n printers -t label_defn_item_values  -d dosis2 $BACKUP_FILE
        elif [ "${BACKUP_TYPE}" = "-c" ]; then
            /usr/bin/pg_restore -U dsuper -F c -v -n printers -t label_defn_item_values  -d dosis2 $BACKUP_FILE
        else
            echo "Invalid backup extension, needs to be .cus or .tar"
        fi

}

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

trap : 0

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

