#!/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>
#
# Debian package post installation script steps:
#  1) Collect mysql root password (optional)
#  2) Download OpenEMR from official github repository
#  3) Install OpenEMR
#  4) Configure OpenEMR (if applicable)
#
# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <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
   configure)

      #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
      INSTALL_USER=gitopenemr
      INSTALL_DATABASE=gitopenemr
      #web user and group
      WEB_GROUP=www-data
      WEB_USER=www-data
      #auto installer location
      INST=$OPENEMR/contrib/util/installScripts/InstallerAuto.php
      INSTTEMP=$OPENEMR/contrib/util/installScripts/InstallerAutoTemp.php

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

      #Standardized exit functions to be used
      #  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 insert variables into config files
      # 1st param is variable name, 2nd param is variable, 3rd param is filename
      insert_var () {
         sed -i 's@^[ 	]*'"$1"'[ 	=].*$@'"$1"' = '"$2"'@' "$3"
      }

      #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 scripting information from config file
      PROCESS=$(collect_var process $CONFIG)
      PLAN=$(collect_var plan $CONFIG)

      #Don't allow re-configuration
      if [ "$PROCESS" == "complete" ] ; then
         unable_exit "OpenEMR has already been configured."
      elif [ "$PROCESS" == "pending" ] ; then
         #continue with configuration
         log_only "Configuring git-openemr package..."
      else
         unable_exit "Error reading process variable in configuration file."
      fi

      if [ "$PLAN" == "upgrade" ] ; then       
         #upgrade is not available with the git-openemr package
         log_only "Upgrading is not available with the git-openemr package"
         log_only "This package is for testing most recent development (unstable) OpenEMR version"
         prompt_input git-openemr/upgrade_not_supported critical ret_result 
         unable_exit "To upgrade to most recent git version, recommend removing/reinstalling package"

      elif [ "$PLAN" == "install" ] ; then
         #continue with installation
         log_only "Installing git-openemr package..."
      else
         unable_exit "Error reading plan variable in configuration file."
      fi      

      #collect the mysql root password (if applicable)
      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_install_${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/no_configure_mysql_root high ret_result
                  log_only "Will install OpenEMR, however will not configure OpenEMR. (unable to provide root password)"
                  break
               fi
            fi
            let "COUNTDOWN += 1"
         done
      fi

      #decide whether to configure OpenEMR after it is installed
      configure_flag=true 
      if check_mysql "$MPASS" "mysql"; then
         #before auto configuration, ensure the openemr user and database do not exist
         # Check for openemr database in mysql, if exist then will not configure
         if check_mysql "$MPASS" "$INSTALL_DATABASE"; then
            prompt_input git-openemr/no_configure_mysql_database high ret_result
            log_only "Will install OpenEMR, however will not automatically configure OpenEMR. (MySQL database already exists)"
            configure_flag=false;
         fi
         # Check for OpenEMR user in mysql.user, if exist then will not configure
         USER=$(mysql -s -u root -h localhost --password="$MPASS" -e "SELECT User from mysql.user where User='$INSTALL_USER'")
         if [ "$USER" == "$INSTALL_USER" ]; then
            prompt_input git-openemr/no_configure_mysql_user high ret_result
            log_only "Will install OpenEMR, however will not automatically configure OpenEMR. (MySQL user already exists)"
            configure_flag=false;
         fi
      else
         #the mysql root password didn't work, so do not configure OpenEMR
         log_only "Will install OpenEMR, however will not automatically configure OpenEMR. (root password did not work)"
         configure_flag=false;
      fi

      #Create directory
      TMPDIR=(`mktemp -d`)
      cd $TMPDIR

      # Download development version of openemr
      log_only "Downloading official OpenEMR development version (please be patient)"
      if !(git clone git://github.com/openemr/openemr.git >> $LOG 2>&1); then
         # unable to download OpenEMR
         prompt_input git-openemr/unable_download critical ret_result
         unable_exit "Unable to download OpenEMR development version"
         exit 1
      fi

      # Remove .git directory
      rm -rf `find $TMPDIR -name .git`

      # Install openemr
      if $configure_flag; then
         log_only "Installing/Configuring OpenEMR development version..."
      else
         log_only "Installing OpenEMR development version..."
      fi
      mv $TMPDIR/openemr $OPENEMR
      cd $OPENEMR
      rmdir $TMPDIR

      #secure openemr 
      chown -Rf root:root $OPENEMR 

      # Set file and directory permissions
      chmod 666 $SITEDIR/sqlconf.php
      chown $WEB_GROUP.$WEB_USER $OPENEMR/interface/modules/zend_modules/config/application.config.php
      chown -R $WEB_GROUP.$WEB_USER $SITEDIR/documents
      chown -R $WEB_GROUP.$WEB_USER $SITEDIR/edi
      chown -R $WEB_GROUP.$WEB_USER $SITEDIR/era
      chown -R $WEB_GROUP.$WEB_USER $SITEDIR/letter_templates
      chown -R $WEB_GROUP.$WEB_USER $OPENEMR/interface/main/calendar/modules/PostCalendar/pntemplates/cache
      chown -R $WEB_GROUP.$WEB_USER $OPENEMR/interface/main/calendar/modules/PostCalendar/pntemplates/compiled
      chown -R $WEB_GROUP.$WEB_USER $OPENEMR/gacl/admin/templates_c

      # NEED TO CONFIGURE APACHE BEFORE CONFIGURATION SINCE ZEND SUPPORT NEEDS PROPER CONFIGURATION
      # Activate the OpenEMR conf file for apache
      log_only "Activate OpenEMR config file for Apache"
      a2ensite git-openemr.conf
      # Ensure the apache rewrite module is turned on
      a2enmod rewrite
      # Restart the apache server
      log_only "Restarting Apache service..."
      invoke-rc.d apache2 restart >> $LOG 2>&1

      #CONFIGURE OPENEMR
      if $configure_flag; then
         # Create a random password for the openemr mysql user
         password=$(makepasswd --char=12)

         # openemr installation VARIABLES
         if [ "$MPASS" == "" ] ; then
            rootpass="rootpass=BLANK" #MySQL server root password
         else
            rootpass="rootpass=$MPASS" #MySQL server root password
         fi
         login="login=$INSTALL_USER" #username to MySQL openemr database
         pass="pass=$password" #password to MySQL openemr database
         dbname="dbname=$INSTALL_DATABASE" #MySQL openemr database name
 
         # 
         # Run Auto Installer 
         #
         sed -e 's@^exit;@ @' <$INST >$INSTTEMP
         php -f $INSTTEMP $rootpass $login $pass $dbname >> $LOG 2>&1
         rm -f $INSTTEMP

         # NO NEED to secure files since this is a development/testing version

         log_only "Done configuring OpenEMR"
      fi

      #update config file, change process to complete and remove plan and pass
      sed -i "s/^[ 	]*process[ 	=].*$/process=complete/" $CONFIG
      sed -i "/^[ 	]*plan[ 	=].*$/d" $CONFIG
      sed -i "/^[ 	]*pass[ 	=].*$/d" $CONFIG

      log_only "You can now use OpenEMR development version by browsing to:"
      log_only "http://localhost/git-openemr"
      if $configure_flag; then
         prompt_input git-openemr/success_install_config high ret_result
         log_only "user is 'admin' and password is 'pass'"
      else 
         prompt_input git-openemr/success_install high ret_result
      fi
      log_only "See the openemr man page for further instructions:"
      log_only "type 'man git-openemr' at command line"

      #stop db
      db_stop

      exit 0
   ;;
   abort-upgrade|abort-remove|abort-deconfigure)
   
      echo "postinst asked to do $1"
      exit 0
   ;;
   *)
      echo "postinst called with unknown argument \`$1'" >&2
      exit 1
   ;;
esac

sleep 5
exit 0
