#!/usr/local/bin/bash

# Name of the back up directory
BACKUP_DIR=backup-configs

while [ "$#" -ne 0 ]
do
  case ${1} in
    --non-interactive)
      INTERACTIVE="no"
      ;;

    *)
      echo "Unknown option: ${1}"
      exit 3
      ;;

    esac
    shift #always consume 1
done

if [ ! -d $BACKUP_DIR ]
then
        echo "No such directory: $BACKUP_DIR"
        exit 1
fi

if [ ! -f $BACKUP_DIR/fs.tar.gz -o ! -f $BACKUP_DIR/pds.tar.gz ]
then
        echo "Invalid backup directory: $BACKUP_DIR"
        exit 2
fi

if [ -f /var/run/sipxpbx/watchdog.pid ]
then
        echo "The sipX daemons appear to be running. You must shut it down to restore."
        exit
fi

if [ ! -f /var/run/postmaster*.pid ]
then
        echo "PostgreSQL does not appear to be running. You must start it to restore."
        exit
fi

echo "Will restore backed up configuration files and database from:"
echo "    `pwd`/$BACKUP_DIR"
echo

if [ "`whoami`" == root ]
then
        TARFLAGS=
else
        TARFLAGS="--exclude etc/init.d/watchdog"
        echo "Will exclude /etc/init.d/watchdog from restore, because you are not root."
        echo
fi

if [ "$INTERACTIVE" = "yes" ]; then
  while :
  do
        echo -n "Is this correct? [y/N] "
        read response
        case $response in
                y* | Y*)
                        echo "Excellent!"
                        break
                ;;
                n* | N* | "")
                        echo "Cancelled."
                        echo
                        exit
                ;;
        esac
  done
fi
echo

echo -n "Restoring configuration files... "
tar xzC / $TARFLAGS < $BACKUP_DIR/fs.tar.gz
echo "done."

echo -n "Restoring database... "
dropdb -U pgsql SIPXCONFIG > /dev/null
createdb -U pgsql --encoding=UNICODE SIPXCONFIG > /dev/null
zcat $BACKUP_DIR/pds.tar.gz | pg_restore -U pgsql -d SIPXCONFIG 2> /dev/null
echo "done."
