#!/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: Amalu Obinna <amaluobinna@aol.com>
#          Brady Miller <brady.g.miller@gmail.com>
#
# Un-install script steps:
#  1) Warn and confirm the user wants to remove the package (mandatory)
#  2) Collect the MySQL root user password (mandatory)
#  3) Remove openemr MySQL database(s)
#  4) Remove openemr MySQL user(s)
#  5) Remove OpenEMR etc directory
#  6) Remove rest of OpenEMR web directory
#  7) Remove tmp directory
#  8) Remove OpenEMR apache configuration
#
#
# 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/openemr
      LOG=$LOGDIR/install
      CONFIGDIR=/etc/openemr
      CONFIG=$CONFIGDIR/openemr.conf
      TMPDIR=/tmp/openemr-tmp
      WEB=/var/www
      OPENEMR=$WEB/openemr
      SITEDIR=$OPENEMR/sites

      #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'"
      }

      #Confirm that user really wants to uninstall
      prompt_input openemr/confirm_remove critical ret_result
      if [ "$ret_result" == "no" ]; then
         unable_exit "You have chosen to not uninstall the OpenEMR package."
      fi

      #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 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 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)

      for dir in $(find $SITEDIR/* -maxdepth 0 -type d ); do
         #collect sitename
         SITENAME=$(basename "$dir")

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

         #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: $SQLDATABASE"
         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: $SQLUSER"
      done

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

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

      #remove tmp directory
      rm -fr $TMPDIR
      log_only "Removed OpenEMR tmp directory"

      #removes the configuration section for OpenEMR in Apache config file (deprecated, but keeping for older packages)
      if [ -f /etc/apache2/httpd.conf ]; then
          sed -i '/#This is the start of the Apache configuration for OpenEMR./,/#This is the end of the Apache configuration for OpenEMR./d' /etc/apache2/httpd.conf
          log_only "Removed OpenEMR Apache configuration in /etc/apache2/httpd.conf"
      fi

      #remove OpenEMR apache set up as active config
      log_only "Turn off apache conf for OpenEMR"
      a2dissite 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
