#!/bin/bash

if [[ "$EUID" -ne 0 ]]; then
  echo "Error: This script must be run as root." >&2
  exit 1
fi

TMP_DIR="/tmp/$$"
FILE_TO_RESTORE=$1
FROM_HARDLOCK=$2

DB_NAME="pos"
CUR_DIR=`pwd`
POSTGRES_VERSION=`ls /etc/postgresql`

if [ "$FILE_TO_RESTORE" = "" ]; then
  echo "Usage: $0 <file_to_restore>"
  exit
fi

if [ "$FROM_HARDLOCK" = "" ]; then
  echo "Will restore $FILE_TO_RESTORE"

  if [ ! -e "$FILE_TO_RESTORE" ]; then
    echo "Can't find $FILE_TO_RESTORE"
    exit
  fi

  if [ -d "/opt/pos_restore" ]; then
    rm -rf /opt/pos_restore
  fi

  mkdir /opt/pos_restore

  echo "Extracting zip file..."
  unzip -q -d /opt/pos_restore $FILE_TO_RESTORE

  if [ $? -eq 0 ]; then

    # if this file doesn't exists, it means we're restoring
    # a backup made with the old backup method
    if [ -e "/opt/pos_restore/db.tgz" ]; then
      #echo "Restarting database..."
      /etc/init.d/postgresql stop
      /etc/init.d/postgresql start
      sleep 3

      # Make sure no one can connect to this database except you
      psql -U postgres -c "UPDATE pg_database SET datallowconn=false WHERE datname='pos';" >>/dev/null 2>&1

      # Drop all existing connections except for yours
      psql -U postgres -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'pos' AND pid <> pg_backend_pid();" >>/dev/null 2>&1

      echo "Droping database..."
      dropdb -U root pos

      echo "Creating database..."
      createdb -U root pos

      echo "Restoring database..."

      valid=`gzip -t /opt/pos_restore/db.tgz 2> /dev/null`

      if [ $? -eq 0 ]; then
        gunzip < /opt/pos_restore/db.tgz | psql -U root $DB_NAME >>/dev/null 2>&1
      else
        pg_restore -U root -Fc -d $DB_NAME /opt/pos_restore/db.tgz
      fi

      # umount tmpfs
      /opt/pos/common/bin/setup_ram_disks.sh 1

      mv /opt/pos /opt/pos.old
      mv /opt/pos_restore /opt/pos

      echo "Restarting software..."
      ps xa | grep "/opt/pos/common/bin/pos" | grep -v grep | awk '{ print $1 }' | sudo xargs kill -9 2> /dev/null

      rm -rf /opt/pos.old

      # mount tmpfs
      /opt/pos/common/bin/setup_ram_disks.sh

      echo "Done."
      exit
    else
      # we'll remove this folder and allow the process to continue to use
      # the old restore method
      rm -rf /opt/pos_restore
    fi

  else
    echo "Error extracting... aborting restore..."
    exit
  fi

fi

BACKUP_DIR=`dirname $FILE_TO_RESTORE`

mkdir $TMP_DIR
cd $TMP_DIR

if [ -e "/opt/pos/etc/coordinates.block" ]; then
  rm -rf /opt/pos/etc/coordinates.block
fi

unzip -q -o "$FILE_TO_RESTORE"

if [ -d "$TMP_DIR/server/data/product_images" ]; then
  rm -rf "$TMP_DIR/server/data/product_images/*"
fi

if [ -d "$TMP_DIR/server/data/group_images" ]; then
  rm -rf "$TMP_DIR/server/data/group_images/*"
fi

if [ -d "$TMP_DIR/common/bin" ]; then
  chmod 755 -R $TMP_DIR/common/bin/*
fi

if [ -d "$TMP_DIR/server/apps" ]; then
  chmod 755 -R $TMP_DIR/server/apps/*
fi

if [ -d "$TMP_DIR/station/apps" ]; then
  chmod 755 -R $TMP_DIR/station/apps/*
fi

mv $TMP_DIR/common/bin/pos /tmp
cp -r $TMP_DIR/* /opt/pos
rm -rf $TMP_DIR

cd /opt/pos

if [ -e "/opt/pos/server/data/database/db.dump" ]; then
  if [ -e "/etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf.open" ] && [ -e "/etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf.close" ]; then
    cp /etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf.close /etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf
  fi

  /etc/init.d/postgresql stop
  /etc/init.d/postgresql start
  sleep 3

  # Make sure no one can connect to this database except you
  psql -U postgres -c "UPDATE pg_database SET datallowconn=false WHERE datname='pos';" >>/dev/null 2>&1

  # Drop all existing connections except for yours
  psql -U postgres -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'pos' AND pid <> pg_backend_pid();" >>/dev/null 2>&1

  dropdb -U root pos
  createdb -U root pos

  #pg_restore -U root -Fc -d $DB_NAME "/opt/pos/server/data/database/db.dump"
  echo "Will restore /opt/pos/server/data/database/db.dump"

  valid=`gzip -t /opt/pos/server/data/database/db.dump 2> /dev/null`

  if [ $? -eq 0 ]; then
    gunzip < /opt/pos/server/data/database/db.dump | psql -U root $DB_NAME >>/dev/null 2>&1
  else
    pg_restore -U root -Fc -d $DB_NAME /opt/pos/server/data/database/db.dump
  fi

  # reindex most used tables
  reindexdb -U root pos -t sales_headers
  reindexdb -U root pos -t sales_payments
  reindexdb -U root pos -t sales_details
  reindexdb -U root pos -t sales_headers_aux
  reindexdb -U root pos -t sales_hashes
  reindexdb -U root pos -t counters

  if [ -e "/opt/pos/doc/casts.postgres" ]; then
    psql -U root pos < /opt/pos/doc/casts.postgres >>/dev/null 2>&1
  fi

  if [ -e "/opt/pos/doc/db_changes.postgres" ]; then
    psql -U root pos < /opt/pos/doc/db_changes.postgres >>/dev/null 2>&1
  fi

  rm -rf "/opt/pos/server/data/database/db.dump"

  if [ -e "/etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf.open" ] && [ -e "/etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf.close" ]; then
    cp /etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf.open /etc/postgresql/$POSTGRES_VERSION/main/postgresql.conf
    /etc/init.d/postgresql stop
    /etc/init.d/postgresql start
    sleep 3
  fi

  rm /tmp/server_*.txt 2> /dev/null
fi

# restore archived files
if [ -d "$BACKUP_DIR/archive" ]; then
  for archive in `ls $BACKUP_DIR/archive`; do
    echo "Will restore from ARCHIVE: $archive"
    date_str=`echo $archive | cut -f1 -d"."`

    # check if is a valid ziped file
    valid=`gzip -t $BACKUP_DIR/archive/$archive 2> /dev/null`

    if [ $? -eq 0 ]; then
      createdb -U root $$

      gunzip < $BACKUP_DIR/archive/$archive | psql -U root $$ >>/dev/null 2>&1

      echo "  sales_headers_$date_str"
      pg_dump -U root $$ --table=sales_headers_$date_str > /tmp/restore.$$.sql
      cat /tmp/restore.$$.sql | psql -U root $DB_NAME >>/dev/null 2>&1

      echo "  sales_payments_$date_str"
      pg_dump -U root $$ --table=sales_payments_$date_str > /tmp/restore.$$.sql
      cat /tmp/restore.$$.sql | psql -U root $DB_NAME >>/dev/null 2>&1

      echo "  sales_hashes_$date_str"
      pg_dump -U root $$ --table=sales_hashes_$date_str > /tmp/restore.$$.sql
      cat /tmp/restore.$$.sql | psql -U root $DB_NAME >>/dev/null 2>&1

      echo "  sales_hashes_products_$date_str"
      pg_dump -U root $$ --table=sales_hashes_products_$date_str > /tmp/restore.$$.sql
      cat /tmp/restore.$$.sql | psql -U root $DB_NAME >>/dev/null 2>&1

      echo "  sales_details_$date_str"
      pg_dump -U root $$ --table=sales_details_$date_str > /tmp/restore.$$.sql
      cat /tmp/restore.$$.sql | psql -U root $DB_NAME >>/dev/null 2>&1

      dropdb -U root $$
    else
      pg_restore --table=sales_headers_$date_str -U root -Fc -d $DB_NAME $BACKUP_DIR/archive/$archive
      pg_restore --table=sales_payments_$date_str -U root -Fc -d $DB_NAME $BACKUP_DIR/archive/$archive
      pg_restore --table=sales_hashes_$date_str -U root -Fc -d $DB_NAME $BACKUP_DIR/archive/$archive
      pg_restore --table=sales_hashes_products_$date_str -U root -Fc -d $DB_NAME $BACKUP_DIR/archive/$archive
      pg_restore --table=sales_details_$date_str -U root -Fc -d $DB_NAME $BACKUP_DIR/archive/$archive
    fi
  done
fi

# fix encodings
if [ -e "/opt/pos/common/bin/fix_encodings.pl" ]; then
  /opt/pos/common/bin/fix_encodings.pl
fi

if [ -e "/opt/pos/etc/config.xml" ] && [ -d "/root/weckOFFICE" ]; then
  cp "/opt/pos/etc/config.xml" /root/weckOFFICE/etc/config.xml
fi

if [ -e "/tmp/pos" ]; then
  mv /tmp/pos /opt/pos/common/bin
fi

cd "$CUR_DIR"

