#!/bin/bash

# There are three ways to install:
# - tarball
# - git
# - packages
# So we need to figure out what type, where it was installed, and what to uninstall.


# Don't run this as a koha user!
if [[ "$USER" =~ "koha" ]]; then
   echo "Do not run this script as a koha user."
   exit 1
fi

# So they shouldn't have to keep typing the sudo password.
echo "Please be prepared to type in your password."
CHKSUDO=`sudo dpkg -l | grep perl | wc -l`
RESULT=$?
if [[ "$RESULT" -ne "0" || "$CHKSUDO" -eq "0" ]]; then
   echo "There is an unexplainable lack of sudo capability or perl. Aborting."
   exit 1
fi

# using mktemp to generate a temporary file for our XML_READ helper script.
CHKMKTEMP=`which mktemp`
if [[ "${#CHKMKTEMP}" -eq "0" || ! -e $CHKMKTEMP ]]; then
   echo "Unable to find mktemp. Aborting!"
   exit 1
fi

# The script uses perl, so it better exist.
PERL=`which perl`
if [[ "${#PERL}" -eq "0" || ! -e $PERL ]]; then
   echo "Unable to find perl. Aborting!"
   exit 1
fi

# Okay, let's go looking for /etc/koha
# packages and tarball installations have it.
PKG_HARD=0
GIT_HARD=0
TARBALL_HARD=0
PKG=0
GIT=0
TARBALL=0
echo "Looking for /etc/koha. This is typically for package installations or tarball installations."
if [ -d /etc/koha ]; then
   echo "Checking for the /etc/koha/sites directory. Package installations use this for each instance."
   if [ -d /etc/koha/sites ]; then
      CHKPKG=`ls /etc/koha/sites 2> /dev/null | wc -l`
      if [ "$CHKPKG" -gt "0" ]; then
         PKG_HARD=1
         if [ "$CHKPKG" -gt "1" ]; then
            echo "You have more than once instance and are likely running a packages installation."
            echo "Please use sudo koha-remove <instance> for each instance instead."
            echo "And then sudo apt-get remove koha-common. Aborting!"
            exit 1
         else
            if [ "X$KOHA_CONF" == "X" ]; then
               KOHA_CONF=`find /etc/koha/sites -name "koha-conf.xml"`
               echo "\$KOHA_CONF set to $KOHA_CONF"
            fi
         fi
      else
         TARBALL_HARD=1
         if [ "X$KOHA_CONF" == "X" ]; then
            KOHA_CONF=`find /etc/koha -name "koha-conf.xml"`
            echo "\$KOHA_CONF set to $KOHA_CONF"
         fi
      fi
   else
      TARBALL_HARD=1
      if [ "X$KOHA_CONF" == "X" ]; then
         KOHA_CONF=`find /etc/koha -name "koha-conf.xml"`
         echo "\$KOHA_CONF set to $KOHA_CONF"
      fi
   fi
else
   GIT_HARD=1
   if [ "X$KOHA_CONF" == "X" ]; then
      CHKCOUNT=0
      while read CHKDIR; do
         if [ -d $CHKDIR/.git ]; then
            echo "Found a git directory."
         else
            CHKCOUNT=$(($CHKCOUNT + 1))
         fi
      done < <(find ~ -name "koha-conf.xml" | cut -f1-4 -d"/" | sort -u)
      if [ "$CHKCOUNT" -ne "1" ]; then
         echo "I found $CHKCOUNT possible koha-conf.xml directories. Aborting!"
         exit 1
      fi
      while read CHKDIR; do
         if [ ! -d $CHKDIR/.git ]; then
            if [ "X$KOHA_CONF" == "X" ]; then
               KOHA_CONF=`find $CHKDIR -name "koha-conf.xml"`
               echo "\$KOHA_CONF set to $KOHA_CONF"
            fi
         fi
      done < <(find ~ -name "koha-conf.xml" | cut -f1-4 -d"/" | sort -u)
   fi
fi

# MUST HAVE $KOHA_CONF DEFINED!
if [ "X$KOHA_CONF" == "X" ]; then
   echo "\$KOHA_CONF is not defined. Unable to uninstall."
   exit 1
fi

# The general installation is based on MySQL, if they don't have MySQL, we'll abort.
MYSQL=`which mysql 2> /dev/null`
MYSQLDUMP=`which mysqldump 2> /dev/null`

if [[ "${#MYSQL}" -eq "0" || ! -e $MYSQL ]]; then
   echo "MySQL is not in an expected location. Aborting!"
   exit 1
fi

if [[ "${#MYSQLDUMP}" -eq "0" || ! -e $MYSQLDUMP ]]; then
   echo "MySQL dump is not in an expected location. Aborting!"
   exit 1
fi

# Create a nice temporary script to read our XML configuration file.
XML_READ=`mktemp`
echo "#!$PERL" >> $XML_READ
echo >> $XML_READ
echo "use XML::LibXML;" >> $XML_READ
echo >> $XML_READ
echo "my (\$parse," >> $XML_READ
echo "    \$xmldoc," >> $XML_READ
echo "    \$sample," >> $XML_READ
echo "   );" >> $XML_READ
echo >> $XML_READ
echo "\$parse = XML::LibXML->new();" >> $XML_READ
echo "\$xmldoc = \$parse->parse_file(\"$KOHA_CONF\");" >> $XML_READ
echo "for \$sample (\$xmldoc->findnodes(\"\$ARGV[0]\")) {" >> $XML_READ
echo "   print \$sample->textContent();" >> $XML_READ
echo "}" >> $XML_READ
chmod 755 $XML_READ

# Where is the install log?
INSTALL_LOG=`sudo $XML_READ yazgfs/config/install_log`

# Grab the database user name
DB_USER=`sudo $XML_READ yazgfs/config/user`

# Grab the database password
DB_PASS=`sudo $XML_READ yazgfs/config/pass`

# So where are the biblio and authories config files for Zebra?
BIBZEBIDX=`sudo $XML_READ yazgfs/server/config | sort -u | grep bib`
AUTHZEBIDX=`sudo $XML_READ yazgfs/server/config | sort -u | grep auth`

# Are we running packages?
PKG=`sudo dpkg -l | grep koha-common | wc -l`

# Are we running git/dev? the INTRANETDIR will have a .git subdirectory.
# Determine the INTRANETDIR.
INTRANETDIR=`sudo $XML_READ yazgfs/config/intranetdir`

# Is there a .git subdirectory?
sudo ls $INTRANETDIR/.git &> /dev/null
RESULT=$?
if [ "$RESULT" -eq "0" ]; then
   GIT=1
else
   GIT=0
fi

# If it isn't packages or git, it is likely a tarball.
if [[ "$PKG" -eq "0" && "$GIT" -eq "0" ]]; then
   TARBALL=1
else
   TARBALL=0
fi

# No sense keeping it if we aren't using it now.
rm $XML_READ

# We should only try uninstalling if we know there is one kind of installation.
# so let's do some sanity checks.
SANITY=$(($PKG + $GIT + $TARBALL))
if [ "$SANITY" -ne "1" ]; then
   echo "Unable to determine what kind of installation you have. Aborting."
   exit 1
fi

SANITY=$(($PKG_HARD + $GIT_HARD + $TARBALL_HARD))
if [ "$SANITY" -ne "1" ]; then
   echo "Unable to determine what kind of installation you have. Aborting."
   exit 1
fi

if [[ "$PKG" -ne "$PKG_HARD" || "$TARBALL" -ne "$TARBALL_HARD" || "$GIT" -ne "$GIT_HARD" ]]; then
   echo "Unable to determine what kind of installation you have. Aborting."
   exit 1
fi

# Tell the user what kind of installation they have.
if [ "$PKG" -eq "1" ]; then
   echo "You likely have a packages installation."
elif [ "$GIT" -eq "1" ]; then
   echo "You likely have a git installation."
else
   echo "You likely have a tarball installation."
fi

# Check if there are koha databases.
LOGIN="--user=$DB_USER --password=$DB_PASS"
CHKDBS=`$MYSQL -B -N -e "show databases;" $LOGIN | grep koha | wc -l`
if [ "$CHKDBS" -eq "0" ]; then
   echo "Unable to find koha related databases. Aborting!"
   exit 1
fi

# Dump backups of the instances/database.
echo "We will dump copies of the database(s), in case you make a mistake."
while read DB2dump; do
   $MYSQLDUMP $LOGIN --databases $DB2dump > ~/${DB2dump}.sql
   RESULT=$?
   if [ "$RESULT" -ne "0" ]; then
      rm ~/${DB2dump}.sql
      echo "Problem dumping ~/${DB2dump}.sql"
   else
      echo "Dumped ~/${DB2dump}.sql"
   fi
done < <($MYSQL -B -N -e "show databases;" $LOGIN | grep koha)

# Prompt for confirmation TWICE.
echo
echo -n "Directories and files will be irrecoverably deleted. Are you sure (y/n)? "
FLAG=0
while [ "$FLAG" -eq "0" ]; do
   read ANSWER
   if [[ "${ANSWER:0:1}" =~ [yYnN] ]]; then
      FLAG=1
   else
      echo "Please type 'y' or 'n' followed by enter/return"
   fi
done

if [[ "$ANSWER" =~ [nN] ]]; then
   echo "Aborting!"
   exit 1
else
   echo -n "There is no turning back. Are you sure (y/n)? "
fi

FLAG=0
while [ "$FLAG" -eq "0" ]; do
   read ANSWER
   if [[ "${ANSWER:0:1}" =~ [yYnN] ]]; then
      FLAG=1
   else
      echo "Please type 'y' or 'n' followed by enter/return"
   fi
done

if [[ "$ANSWER" =~ [nN] ]]; then
   echo "Aborting!"
   exit 1
else
   echo "Processing will continue."
fi

if [ ! -d /etc/apache2/sites-enabled ]; then
   echo "Apache2 sites-enabled is not configured as expected. Aborting!"
   exit 1
fi

if [ ! -d /etc/apache2/sites-available ]; then
   echo "Apache2 sites-available is not configured as expected. Aborting!"
   exit 1
fi

DAEMONCOUNT=`ls /etc/init.d/*koha* 2> /dev/null | wc -l`
if [ "$DAEMONCOUNT" -eq "0" ]; then
   echo "Missing expected Zebra daemon files. Aborting!"
   exit 1
fi

if [ "${#BIBZEBIDX}" -eq "0" ]; then
   echo "Unable to find zebra biblio indexing configuration files. Aborting!"
   exit 1
fi

if [ "${#AUTHZEBIDX}" -eq "0" ]; then
   echo "Unable to find zebra authorities indexing configuration files. Aborting!"
   exit 1
fi

CHKCROND=`sudo ls /etc/cron.d/*koha* 2> /dev/null | wc -l`
if [ "$CHKCROND" -eq "0" ]; then
   echo "Unable to find koha crontab files. Aborting!"
   exit 1
fi

CHKDIRS=`grep koha $INSTALL_LOG | cut -f2 -d'=' | cut -f1-4 -d'/' | grep ^\/ | sort -u | wc -l`
if [ "$CHKDIRS" -eq "0" ]; then
   echo "Unable to determine typical directories to delete. Aborting!"
   exit 1
fi

# For packages, we better remove instances.
if [ "$PKG" -eq "1" ]; then
   echo "koha instances being removed..."
   while read INSTANCE; do
      echo "Removing $INSTANCE"
      sudo koha-remove $INSTANCE &> /dev/null
   done < <(koha-list)
   sudo apt-get -y remove koha-common &> /dev/null
fi

# This shouldn't hurt for packages now, since it should all be blanked.
# and if it isn't, then it probably needs help. ;)

# First we'll handle apache.
echo "Disabling and removing koha apache site(s)."
while read SITE2DIS; do
   sudo a2dissite `basename $SITE2DIS` &> /dev/null
   sudo rm /etc/apache2/sites-available/`basename $SITE2DIS` &> /dev/null
done < <(sudo grep -l koha /etc/apache2/sites-enabled/*)
echo "Restarting apache2."
sudo /etc/init.d/apache2 restart &> /dev/null

# Next we'll work on the koha-zebra-daemon.
echo "Removing koha-zebra-daemon."
while read DAEMON; do
   sudo $DAEMON stop
   sudo update-rc.d `basename $DAEMON` remove
   sudo rm $DAEMON
done < <(ls /etc/init.d/*koha* 2> /dev/null)

# Next we'll drop the database
echo "koha databases being removed..."
while read DB2dump; do
   mysql $LOGIN -e "drop database $DB2dump;" &> /dev/null
   RESULT=$?
   if [ "$RESULT" -ne "0" ]; then
      echo "Problem dropping ${DB2dump}"
   else
      echo "Dropped ${DB2dump}"
   fi
done < <($MYSQL -B -N -e "show databases;" $LOGIN 2> /dev/null | grep koha)

# Cleaning up the Zebra Indexes
echo "Cleaning up the Zebra Indexes"
echo "Biblios..."
sudo zebraidx -c $BIBZEBIDX -g iso2709 -d biblios init &> /dev/null
echo "Authorities..."
sudo zebraidx -c $AUTHZEBIDX -g iso2709 -d authorities init &> /dev/null

# remove the crontab job
echo "Removing Crontab jobs..."
sudo rm `ls /etc/cron.d/*koha*` &> /dev/null

# a whole bunch of installation directories.
echo "Directories being deleted."
while read DIR2DEL; do
   echo "$DIR2DEL being deleted..."
   sudo rm -rf $DIR2DEL &> /dev/null
done < <(grep koha $INSTALL_LOG 2> /dev/null | cut -f2 -d'=' | cut -f1-4 -d'/' | grep ^\/ | sort -u)

# attempting to delete koha users
echo -n "Removing koha users"
while read KOHAUSER; do
   echo "Removing $KOHAUSER"
   sudo deluser $KOHAUSER &> /dev/null
done < <(sudo cat /etc/passwd | cut -f1 -d: | grep koha)

echo "Uninstall complete."