#!/bin/bash

DUMP=ucs.sql
WITHOUT_BACKUP=false

set -- $(getopt hB "$@")
while [ $# -gt 0 ]; do
  case "$1" in
    -h) echo "Usage: $0 [-B] [ucs.sql]"; exit 0 ;;
    -B) WITHOUT_BACKUP=true ;;
    --) ! test -z "$2" && DUMP=$2 ;;
    *) break ;;
  esac
  shift
done

if [ ! -e $DUMP ]; then
  echo "Dump file $DUMP not found!"
  exit 1
fi


source /etc/ucs/ucs.conf
export PGPASSWORD=$DB_PASS
psql_ucs="psql --dbname=$DB_NAME --host=$DB_HOST --username=$DB_USER --no-password -v ON_ERROR_STOP=1"
psql_template1="psql --dbname=template1 --host=$DB_HOST --username=$DB_USER --no-password -At"

MIGRATE_SQL=/etc/ucs/migrate.sql

DB_BACKUP=${DB_NAME}_$(date +%Y%m%dT%H%M%S)

echo
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "!! WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING !!"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo
echo "You are about to _REPLACE_ curent UCS database $DB_NAME at $DB_HOST by $DUMP!"
echo
echo " * UCS will be STOPPED!"
if $WITHOUT_BACKUP; then
  echo " * Current UCS database will _NOT_ be backedup!"
else
  echo " * In case there is $DB_BACKUP database it will be DELETED!"
  echo " * Current UCS database will be renamed to $DB_BACKUP."
fi
echo " * Database ${DB_NAME} will be restored from $DUMP."
echo " * Database ${DB_NAME} will be upgraded to this UCS version."
if [ -e $MIGRATE_SQL ]; then
  echo " * SQL script $MIGRATE_SQL will by applied on restored database."
fi
echo
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "!! WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING !!"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo
read -p'If you are 100% sure type "YES I KNOW WHAT I AM DOING": ' answer
echo
if [ "$answer" != "YES I KNOW WHAT I AM DOING" ]; then
    echo "Terminating..."
    exit 1
fi


for i in {10..1}; do
    echo "Will DELETE database $DB_NAME from $DB_HOST in $i seconds! Press Ctrl+C to terminate."
    sleep 1
done

db_exists() {
  local exists=$($psql_template1 -tAw -c "SELECT 1 FROM pg_catalog.pg_database WHERE datname = '$1';")
  if [ "$exists" = "1" ]; then
    return 0
  fi
  return 1
}

echo " * Stopping UCS..."
systemctl stop ucs


if $WITHOUT_BACKUP; then
  drop_sql=$(mktemp --suffix=.sql)
  echo "BEGIN;" >> $drop_sql
  $psql_ucs -At <<EOF >> $drop_sql
SELECT 'DROP TABLE IF EXISTS ' || schemaname || '.' || tablename || ' CASCADE;'
FROM pg_tables
WHERE tableowner = '$DB_USER';
EOF
  $psql_ucs -At <<EOF >> $drop_sql
SELECT 'DROP SEQUENCE IF EXISTS ' || schemaname || '.' || sequencename || ' CASCADE;'
FROM pg_sequences
WHERE sequenceowner = '$DB_USER';
EOF
  $psql_ucs -At <<EOF >> $drop_sql
SELECT 'DROP FUNCTION ' || ns.nspname || '.' || proname || '(' || oidvectortypes(proargtypes) || ');'
FROM pg_proc
INNER JOIN pg_namespace ns ON (pg_proc.pronamespace = ns.oid)
WHERE proowner::regrole::text = '$DB_USER';
EOF
  echo "COMMIT;" >> $drop_sql
  echo " * Removing current tables, sequences and functions..."
  $psql_ucs < $drop_sql >/dev/null 2>&1
  rm $drop_sql
else
  if db_exists $DB_BACKUP; then
    echo " * Removing old backup database $DB_BACKUP"
    $psql_template1 -c "DROP database $DB_BACKUP"
    if db_exists $DB_BACKUP; then
      echo "Unable to remove old backup database $DB_BACKUP!"
      exit 1
    fi
  fi

  echo " * Renaming $DB_NAME to $DB_BACKUP"
  $psql_template1 -c "ALTER DATABASE $DB_NAME RENAME TO $DB_BACKUP;"
  if db_exists $DB_NAME; then
    echo "FAIL Unable to rename database."
    echo " * Does any process have opened connection to $DB_NAME?"
    echo " * Does $DB_USER has permission to rename database?"
    exit 1
  fi

  echo " * Creating $DB_NAME"
  $psql_template1 -c "CREATE DATABASE $DB_NAME OWNER $DB_USER TEMPLATE = template0 ENCODING = 'UTF-8' LC_COLLATE = 'cs_CZ.UTF-8' LC_CTYPE = 'cs_CZ.UTF-8';"
  if ! db_exists $DB_NAME; then
    echo "Unable to create database $DB_NAME!"
    echo "You can create DB manually by executing following SQL:"
    echo ""
    echo "  CREATE DATABASE $DB_NAME OWNER $DB_USER TEMPLATE = template0 ENCODING = 'UTF-8' LC_COLLATE = 'cs_CZ.UTF-8' LC_CTYPE = 'cs_CZ.UTF-8';"
    echo ""
    exit 1
  fi
fi

echo " * Restoring database from local file $1"
restore_log=$(mktemp --suffix=.log)
$psql_ucs < $DUMP >$restore_log 2>&1
if [ $? -ne 0 ]; then
  echo "Database restore failed. For details check $restore_log"
  exit 1
else
  rm $restore_log
fi

echo " * Upgrading database for current UCS version"

curr=`pwd`
cd /opt/ucs/server/sql
/opt/ucs/server/sql/upgrade.sh
cd $curr

if [ -e $MIGRATE_SQL ]; then
  echo " * Running migration SQL script $MIGRATE_SQL"
  $psql_ucs < $MIGRATE_SQL
  if [ $? -ne 0 ]; then
    echo "Database migration script failed. Not starting UCS."
    exit 1
  fi
fi

echo " * Starting UCS..."
systemctl start ucs
