#!/bin/bash
#
#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.
#
# authors: Brady Miller <brady@sparmy.com>
#          Amalu Obinna <amaluobinna@aol.com>
#
# date:    04/28/09
#
# Debian package pre-installation script steps:
#  1) Create log dir/file
#  2) Ensure cvs-OpenEMR web directory was not previously installed.
#  3) If MySQL is already installed: 
#         -Collect MySQL root password
#         -Ensure no cvs-openemr mysql database or mysql user
#  4) Create config dir/file
#
# Upgrading is not an option here, since this is for testing/evaluation
# of the most current unstable development version of OpenEMR.
#
#  Output log file:
#   /var/log/cvs-openemr/install
#
#
# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

#constants and paths
LOGDIR=/var/log/cvs-openemr
LOG=$LOGDIR/install
CONFIGDIR=/etc/cvs-openemr
CONFIG=$CONFIGDIR/cvs-openemr.conf
TMPDIR=/tmp/cvs-openemr-tmp
WEB=/var/www
OPENEMR=$WEB/cvs-openemr
INSTALL_USER=cvsopenemr
INSTALL_DATABASE=cvsopenemr

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

#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 install the openemr package
#  requires one parameter (string with reason for exiting)
unable_exit () {
   echo $1
   echo "`date`: $1" >> $LOG
   echo "EXITING.........."
   echo "`date`: EXITING.........." >> $LOG
   sleep 5
   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
   echo `mysql -u "$USE" -h "$HOST" --password="$1" -e 'show databases' 2>/dev/null | awk '{ print $1}' | grep "^$2$"`
}

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

case "$1" in
   install)

      #create the log file directory
      mkdir -p $LOGDIR

      #Check for /var/www/cvs-openemr, if exist then exit
      if [ -d "$OPENEMR" ]; then
         unable_exit "OpenEMR is already installed ($OPENEMR), so can not install the OpenEMR Package."
      fi

      #Begin the config file string
      # this is so the postinst script can follow installation
      #  variables:
      #   process states whether installation is pending or complete
      #   plan states install
      #   pass temporarily holds the mysql root password
      SETTING="#Optional settings\n\
#(currently empty, plan to use in subsequent versions if needed)\n\
\n\
#Installation settings\n\
# (DO NOT EDIT below!!!)\n\
process=pending\n\
plan=install"

      #If mysql is installed, then figure out root password      
      MYSQL=$(dpkg -l |grep mysql-server)
      if [ -n "$MYSQL" ]; then

         #set pass to blank as default
         MPASS=""

## BEGIN MYSQL ROOT PASSWORD GRAB
         if [ "`check_mysql "$MPASS" "mysql"`" != "mysql" ]; then
            #the initial mysql password didn't work, so ask for password
            COUNTDOWN=1
            while true; do
               echo ""
               echo -n "Please enter your MySQL root password:"
               read MPASS 
               echo ""   
               if [ "`check_mysql "$MPASS" "mysql"`" == "mysql" ]; then
                  #the mysql root password works, so can exit loop
                  break
               else
                  #the mysql root password did not work
                  if [ "$COUNTDOWN" -ge "5" ]; then
                     output_both "5 attempts to enter your mysql root password have failed"
                     output_both "Recommend repeating OpenEMR installation when you know your mysql root password"
                     unable_exit "Giving up on OpenEMR package installation."
                  fi
                  echo "The entered MySQL root password did not work."
                  echo "$COUNTDOWN of 5 total attempts."
                  echo "PLEASE TRY AGAIN..."
               fi
               let "COUNTDOWN += 1"
            done
         fi
## END MYSQL ROOT PASSWORD GRAB

         #successfully obtained mysql root password, so place it in the temp config file
         SETTING="$SETTING\npass=$MPASS"

         #now ensure the openemr user and database do not exist, if so then exit
         # Check for openemr database in mysql, if exist then exit
         if [ "`check_mysql "$MPASS" "$INSTALL_DATABASE"`" == "$INSTALL_DATABASE" ]; then
            unable_exit "MySQL '$INSTALL_DATABASE' database already exists"
         fi
         # Check for user openemr in mysql.user, if exist then exit
         USER=$(mysql -s -u root -h localhost --password="$MPASS" -e "SELECT User from mysql.user where User='$INSTALL_USER'")
         if [ "$USER" == "$INSTALL_USER" ]; then
            unable_exit "MySQl user '$INSTALL_USER' already exists"
         fi
      fi

      #ready to install package, so create the config directory and files
      mkdir -p $CONFIGDIR
      echo -e $SETTING > $CONFIG

      exit 0
   ;;

   upgrade)

      #upgrade is not available with the cvs-openemr package
      echo ""
      output_both "Upgrading is not available with the cvs-openemr package"
      output_both "This package is for testing most recent development (unstable) OpenEMR version"
      unable_exit "To upgrade to most recent cvs version, recommend removing/reinstalling package"
   ;;

   abort-upgrade)
      echo "preinst asked to do abort-upgrade"
      exit 0
   ;;

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