#!/usr/bin/env bash

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

enforce_root

OS="`getos`"

CONFIG_TAR=""
CURRENT_TIME=$(date "+%Y.%m.%d-%H.%M.%S")
CONFIG_PATH="/tmp/config_to_restore.$CURRENT_TIME"

echo_help() {
	echo "restore-config [-h] [-f]
	-h | --help show help
	-f | --file tarball for config restoration
	"
}

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

echo "RESTORING CONFIGURATION"

warning "Detected ${OS} OS"

mkdir -p $CONFIG_PATH

tar -xvf $CONFIG_TAR -C $CONFIG_PATH

echo "#### Restoring dosis2/etc/custom files ####"
cp -rf $CONFIG_PATH/etc/custom/* /opt/dosis2/etc/custom/.

echo "#### Restoring CUPS config files ####"
cp  -rf $CONFIG_PATH/cups/* /etc/cups/.

echo "#### Restore customer specific files (if they exist) ####"
cp -rf $CONFIG_PATH/customer/* /opt/dosis2/customer/.

echo "#### Restore hosts file ####"
cp -f $CONFIG_PATH/hosts /etc/hosts

echo "#### Restore smbcredentials ####"
cp -f $CONFIG_PATH/.smbcredentials /opt/dosis2/.smbcredentials

echo "#### Restore auto.cifs ####"
cp -f $CONFIG_PATH/auto.cifs /etc/auto.cifs

echo "#### Restore auto.master ####"
cp -f $CONFIG_PATH/auto.master /etc/auto.master

echo "#### Restore dosis_pmis_sync.json ####"
cp -f $CONFIG_PATH/dosis_pmis_sync.json /etc/pmissync/dosis_pmis_sync.json


echo "#### Restore pg_hba.conf file ####"

cp -f $CONFIG_PATH/pg_hba.conf /etc/postgresql/10/main/pg_hba.conf
