#!/bin/bash -e
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
# Copyright 2011-2014
# authors: Brady Miller <brady.g.miller@gmail.com>
#          Amalu Obinna <amaluobinna@aol.com>
#
# Un-install script steps:
#  1) Collect the MySQL root user password (mandatory)
#  2) Remove OpenEMR etc directory
#  3) Remove OpenEMR web directory
#  4) Remove OpenEMR MySQL database
#  5) Remove OpenEMR MySQL user
#
#
# summary of how this script can be called:
#        * <prerm> `remove'
#        * <old-prerm> `upgrade' <new-version>
#        * <new-prerm> `failed-upgrade' <old-version>
#        * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
#        * <deconfigured's-prerm> `deconfigure' `in-favour'
#          <package-being-installed> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

# Source debconf library.
. /usr/share/debconf/confmodule

case "$1" in
   remove)

      #constants and paths
      LOGDIR=/var/log/git-openemr
      LOG=$LOGDIR/install
      CONFIGDIR=/etc/git-openemr
      CONFIG=$CONFIGDIR/git-openemr.conf
      WEB=/var/www
      OPENEMR=$WEB/git-openemr
      SITEDIR=$OPENEMR/sites/default

      #Standardized echo function to send to only log file
      #  requires one parameter (string)
      log_only () {
         echo "`date`: $1" >> $LOG
      }

      #Standardized exit function to be used when unable to uninstall the
      #openemr package
      #  requires one parameter (string with reason for exiting)
      unable_exit () {
         echo "`date`: $1" >> $LOG
         echo "`date`: EXITING.........." >> $LOG
         exit 1
      }

      #function to check mysql for selected databases
      # 1st param is password, 2nd param database, 3rd param is host (optional), 4th param is user (optional)
      check_mysql () {
         if [ -n "$3" ]; then
            HOST=$3
         else
            HOST=localhost
         fi
         if [ -n "$4" ]; then
            USE=$4
         else
            USE=root
         fi

         if [ "`mysql -u "$USE" -h "$HOST" --password="$1" -e 'show databases' 2>/dev/null | awk '{ print $1}' | grep "^$2$"`" == "$2" ]; then
            return 0
         else
            return 1
         fi
      }

      #function to collect variables from config files
      # 1st param is variable name, 2nd param is filename 
      collect_var () {
         echo `grep -i "^[[:space:]]*$1[[:space:]=]" $2 | cut -d \= -f 2 | cut -d \; -f 1 | sed "s/[ 	'\"]//gi"`
      }

      #function to prompt for input
      # 1st param is name, 2nd param is priority, 3rd param is where result gets sent back in
      # return the input
      prompt_input () {
         db_set "$1" ""
         db_fset "$1" seen false
         db_input "$2" "$1" || true
         db_go || true
         db_get "$1"
         local input_value="$RET"
         db_set "$1" ""
         db_fset "$1" seen false
         local __result=$3
         eval $__result="'$input_value'"
      }

      #collect the mysql root password
      MPASS=""
      if check_mysql "$MPASS" "mysql"; then
         log_only "Passed the mysql check loop"
      else
         #the blank initial mysql password didn't work, so prompt for password
         # (will give 3 chances to provide correct password)
         COUNTDOWN=1
         while true; do
            prompt_input git-openemr/mysql_p_remove_${COUNTDOWN} critical ret_result
            MPASS="$ret_result"
            if check_mysql "$MPASS" "mysql"; then
               #the mysql root password works, so can exit loop
               log_only "Passed the mysql check loop"
               break
            else
               #the mysql root password did not work
               if [ "$COUNTDOWN" -ge "3" ]; then
                  prompt_input git-openemr/unable_remove critical ret_result
                  unable_exit "OpenEMR removal attempt failed (can try again when you know the mysql root password)"
               fi
            fi
            let "COUNTDOWN += 1"
         done
      fi

      #collect scripting information from config file
      PROCESS=$(collect_var process $CONFIG)
      PLAN=$(collect_var plan $CONFIG)

      # Collect database information from sqlconf.php file
      SQLLOCATION=$(collect_var \$host $SITEDIR/sqlconf.php)
      SQLUSER=$(collect_var \$login $SITEDIR/sqlconf.php)
      SQLPASSWORD=$(collect_var \$pass $SITEDIR/sqlconf.php)
      SQLDATABASE=$(collect_var \$dbase $SITEDIR/sqlconf.php)

      #remove etc directory
      rm -rf $CONFIGDIR
      log_only "Removed OpenEMR etc directory"

      #remove web directory
      rm -rf $OPENEMR
      log_only "Finished removing OpenEMR web directory"

      #remove openemr mysql database (ensure the database exists)
      if check_mysql "$MPASS" "$SQLDATABASE"; then
         mysqladmin -f -u root -h "$SQLLOCATION" --password="$MPASS" drop "$SQLDATABASE" >> $LOG 2>&1
         log_only "Removed OpenEMR MySQL database"
      fi

      #remove openemr mysql user
      mysql -f -u root -h "$SQLLOCATION" --password="$MPASS" -e "DELETE FROM mysql.user WHERE User = '$SQLUSER';FLUSH PRIVILEGES;" >> $LOG 2>&1
      log_only "Removed OpenEMR MySQL user"

      #remove OpenEMR apache set up as active config
      log_only "Turn off apache conf for OpenEMR"
      a2dissite git-openemr.conf

      #stop db
      db_stop

      exit 0
   ;;

   upgrade)

      #echo "No need for upgrade instructions in prerm script to version $2"
      exit 0
   ;;

   deconfigure)

      echo "prerm asked to do deconfigure"
      exit 0
   ;;

   failed-upgrade)

      echo "prerm asked to do failed-upgrade from version $2"
      exit 0
   ;;

   *)
      echo "prerm called with unknown argument \`$1'" >&2
      exit 1
   ;;
esac
