#!/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:    10/29/2010
#
# Debian package post installation script steps:
#  1) Collect mysql root password
#  2) Download OpenEMR from official github repository
#  3) Install OpenEMR
#  4) Configure OpenEMR
#  5) Echo instructions on starting openemr
#
# 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

case "$1" in
   configure)

      #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
      SITEDIR=$OPENEMR/sites/default
      INSTALL_USER=cvsopenemr
      INSTALL_DATABASE=cvsopenemr
      #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 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 functions to be used
      #  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"`
      }      

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

      #collect scripting information from config file
      PROCESS=$(collect_var process $CONFIG)
      PLAN=$(collect_var plan $CONFIG)
      MPASS=$(collect_var pass $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 cvs-openemr package..."
      else
         unable_exit "Error reading process variable in configuration file."
      fi

      if [ "$PLAN" == "upgrade" ] ; then       
         #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"

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

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

      #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 OpenEMR user 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

      #Go into tmp directory
      mkdir -p $TMPDIR
      cd $TMPDIR

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

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

      # Install openemr
      output_both "Installing/Configuring OpenEMR development version..."
      mv $TMPDIR/openemr $OPENEMR

      #go to openemr directory
      cd $OPENEMR

      #secure openemr 
      chown -Rf root:root $OPENEMR 

      #INSTALL AND CONFIGURE OPENEMR
      # 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
 
      # Set file and directory permissions 
      chmod 666 $OPENEMR/library/sqlconf.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 $OPENEMR/library/freeb 
      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 
      # 
      # Run Auto Installer 
      #
      sed -e 's@^exit;@ @' <$INST >$INSTTEMP
      php -f $INSTTEMP $rootpass $login $pass $dbname >> $LOG
      rm -f $INSTTEMP 

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

      log_only "Done configuring OpenEMR"

      output_both "Restarting Apache service..."
      invoke-rc.d apache2 restart >> $LOG

      #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

      echo "--------------------------------------------------"
      echo ""
      output_both "You can now use OpenEMR development version by browsing to:"
      output_both "http://localhost/cvs-openemr"
      output_both "user is 'admin' and password is 'pass'"
      echo ""
      output_both "See the openemr man page for further instructions:"
      output_both "type 'man cvs-openemr' at command line"
      echo ""
      echo "--------------------------------------------------"

      sleep 5
      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
