#!/bin/bash
# zmsetup
#
# Description:
# This is a basic setup tool for the Mageia installation of ZoneMinder.
# It assumes a default installation using mysql (mariadb) and apache.
# It will check for and if necessary install mysql, start mysql, optionally
# set up a mysql root password and create the ZoneMinder database if 
# required, or update an existing one, setting required db permissions.
# When all is ready it will start Apache, and ZoneMinder and if all is
# well it will give the url of the running ZoneMinder server.
#
# Use:-
# After installation of ZoneMinder run this script as root and answer any questions.
# $ su
# # zmsetup
#===================================
#Changelog
# 18/04/2016 Check timezone is set in php.ini
# 19/11/2015 Set mysql db permissions (removes patch from package)
# 22/03/2014 Add file structure update for 1.27.x
# 17/09/2013 Use zmuser not root to modify db (reverted 22/03/2014)
# 22/03/2013 Check for and install mariadb
# 21/01/2012 Moved all service commands to systemctl
# 10/10/2011 1.25.0 no perf update to db required 
# 25/09/2011  Bug fix 
#===================================
confirm()
# User query interface.
{
par=("$@")
rval=3
while [[ $rval > 2 ]]; do
    echo -n ${par[0]}" "${par[1]}" "
    ans= ; rval=
    read ans
    if [[ -z $ans ]] || [[ ${#ans} > 1 ]]; then
        rval=3
    else
        case $ans in
            [${par[2]}]*)
                rval=0
                ;;
            [${par[3]}]*)
                rval=1
                ;;
            [${par[4]}]*)
                rval=2
                ;;
            *)
                rval=3
                ;;
        esac
    fi
done
    return $rval
}

getdbver() {
dbver=$(mysql zm -u root -p$passwd  -se "SELECT Value FROM Config WHERE Name = 'ZM_DYN_DB_VERSION'")
}
# Special case for update from versions < 1.27.0
struc127updt() {
for dir in events images; do
if [[ -d /var/www/html/zm/$dir ]]; then
  if [[ -d /var/lib/zoneminder/$dir ]]; then
    rm -rf /var/lib/zoneminder/$dir/*
  fi
  echo "Moving $dir - this may take some time ..."
  mv /var/www/html/zm/$dir/* /var/lib/zoneminder/$dir
else
  echo "/var/www/html/zm/$dir was already removed"
fi
done
echo "Removing remaining obsolete zoneminder files/folders from web root ..."
rm -rf /var/www/html/zm
echo "Updating cgi path in database ..."
cgipath=$(mysql zm -u root -p$passwd  -se "SELECT Value FROM Config WHERE Name= 'ZM_PATH_ZMS';")
if echo $cgipath | grep -q "cgi-bin"; then
   mysql zm -u root -p$passwd  -se "UPDATE Config SET Value = '/zmcgi/nph-zms' WHERE Name = 'ZM_PATH_ZMS';"
fi
echo "Updating log path in database ..."
logpath=$(mysql zm -u root -p$passwd  -se "SELECT Value FROM Config WHERE Name= 'ZM_PATH_LOGS';")
if echo $logpath | grep -q "/var/log/zm"; then
   mysql zm -u root -p$passwd  -se "UPDATE Config SET Value = '/var/log/zoneminder' WHERE Name = 'ZM_PATH_LOGS';"
fi
}

check_mysqld()
{
if [[ $(systemctl status mysqld.service|head -n3|grep Loaded:|tr -s ' '|cut -s -d' ' -f3) != loaded ]]; then
if confirm "mysql is not installed, would you like to install it now?" "[y/n]" "Yy" "Nn"; then
urpmi mysql --no-suggests || { echo "Installation failed - please check network and media sources and re-run zmsetup"; exit 0; }
else
echo "You will need to provide a mysql database yourself - aborting zmsetup"
exit 0
fi
fi
if [[ $(systemctl status mysqld.service|head -n3|grep Active:|tr -s ' '|cut -s -d' ' -f3) != active ]]; then
systemctl start mysqld.service
fi

[[ $(systemctl status mysqld.service|head -n3|grep Active:|tr -s ' '|cut -s -d' ' -f3) = active ]] || \
{ echo -e "Aborting zmsetup, see status message :-\n"; systemctl status mysqld.service; exit 0; } 
}

closeall()
{
systemctl stop zoneminder.service > /dev/null 2>&1
systemctl stop httpd.service > /dev/null 2>&1
systemctl stop mysqld.service > /dev/null 2>&1
}

getpass()
{
if mysql -uroot -e 'SELECT 1;' > /dev/null 2>&1 ; then
echo -e "You do not appear to have a mysql root password set.\nYou can complete \
ZoneMinder setup without one, or create one now (really recommended)"
set=0
while [[ $set = 0 ]]; do
if confirm "Do you want to create a mysql root password now?" "[y/n]" "Yy" "Nn"; then
    while true; do  
      read -s -p "New password: " passwd
      echo
      [[ ${#passwd} = 0 ]] && continue
      read -s -p  "Repeat password: " passwd2
      echo
      [[ ${#passwd2} = 0 ]] && continue
      [[ "$passwd" = "$passwd2" ]] || \
      { echo "Passwords differ, please start again"; continue; }
      break
    done
      if confirm "Set new password now - confirm - OK?" "[y/n]" "Yy" "Nn"; then
	echo "Please wait - ..."
	mysqladmin password $passwd
	systemctl restart mysqld.service
	set=1
      else
	set=0
      fi
else
      echo "Remember to set a mysql root password before going live!"
      passwd=
      set=1
fi
done
else
while true ; do
read -s -p "Please enter your mysql root password: " passwd
echo
[[ ${#passwd} = 0 ]] && continue
mysql -uroot -p$passwd -e 'SELECT 1;' > /dev/null 2>&1
[[ $? = 0 ]] && break
done
fi

if [[ ${#passwd} = 0 ]]; then
   mysqlpass=
else
   mysqlpass="-p"$passwd
fi
}

get_cfg() {
if [[ -e /etc/zm.conf ]]; then
zm_db_name=$(cat /etc/zm.conf | grep ZM_DB_NAME | cut -d= -f2)
zm_db_user=$(cat /etc/zm.conf | grep ZM_DB_USER | cut -d= -f2)
zm_db_pass=$(cat /etc/zm.conf | grep ZM_DB_PASS | cut -d= -f2)
fi
}

#----------------------------
chkdb()
{
if mysql -uroot $mysqlpass $zm_db_name -e 'SELECT 1;' > /dev/null 2>&1 ; then
echo "You already have a ZoneMinder database installed"
zmdb=1
else
zmdb=0
fi



if [[ $zmdb = 1 ]] && confirm "Do you want to re-use it?" "[y/n]" "Yy" "Nn"; then
    getdbver
    if [[ $dbver < 1.27 ]]; then
echo -e "Your ZoneMinder database is at version $dbver.\n\
You have recently installed a version of ZoneMinder at or above version 1.27.\n\
The default file structure of ZoneMinder in Mageia changed at version 1.27.\n\
To continue to use your existing database and access stored events, the file structure\n\
needs to be updated.\n\
Before continuing make backups of any important data that may otherwise be lost if this\n\
process fails, which may happen, especially if your file structure is non-standard.\n\
If your events or images folders are mount points then unmount the devices before continuing\n\
as you will need to manually re-configure your fstab.\n\
Read /usr/share/doc/zoneminder/README.1.27.Mageia for more details about the new file layout."
      if confirm "Would you like to read README.1.27.Mageia now?" "[y/n]" "Yy" "Nn"; then
	clear
	cat /usr/share/doc/zoneminder/README.1.27.Mageia
      fi
      if confirm "Continue to update?" "[y/n]" "Yy" "Nn"; then
	struc127updt
      else
	exit 0
      fi
    fi
    if [[ $dbver < 1.28 ]]; then
	echo "Updating sock path in database ..."
        sockpath=$(mysql zm -u root -p$passwd  -se "SELECT Value FROM Config WHERE Name= 'ZM_PATH_SOCKS';")
        if echo $sockpath | grep -q "/tmp/zm"; then
            mysql zm -u root -p$passwd  -se "UPDATE Config SET Value = '/run/zm' WHERE Name = 'ZM_PATH_SOCKS';"
        fi
        echo "Updating swap path in database ..."
        swappath=$(mysql zm -u root -p$passwd  -se "SELECT Value FROM Config WHERE Name= 'ZM_PATH_SWAP';")
        if echo $swappath | grep -q "/tmp/zm"; then
            mysql zm -u root -p$passwd  -se "UPDATE Config SET Value = '/run/zm' WHERE Name = 'ZM_PATH_SWAP';"
        fi
    fi
echo "Updating database structure where necessary ..."
updt=1
else
reuse=0
fi

if ([[ $zmdb = 1 ]] && [[ $reuse = 0 ]]); then
if confirm "Delete existing ZoneMinder database? OK?"  "[y/n]" "Yy" "Nn"; then
mysql -uroot $mysqlpass -e "DROP DATABASE $zm_db_name;"
zmdb=0
else
echo "You must delete the old database before creating a new one - aborting"
exit 0
fi
fi

if [[ $zmdb = 0 ]]; then
echo "Installing a new ZoneMinder database ..."
mysql -uroot $mysqlpass < /usr/share/zoneminder/db/zm_create.sql
setperms
fi

[[ $updt = 1 ]] && updtdb
}
#----------------------------

setperms()
{
mysql -uroot $mysqlpass -e "USE mysql; GRANT ALL PRIVILEGES ON zm.* TO $zm_db_user@localhost IDENTIFIED BY '$zm_db_pass';"
}

updtdb()
{
setperms
zmupdate.pl -u root -p $passwd -d /usr/share/zoneminder/db
}

chkphp() {
if ! $(grep ^date\.timezone /etc/php.ini >/dev/null 2>&1); then
	echo "You do not appear to have a timezone set for php."
	echo -e "This is required for the Web-UI to work.\n"
	if [[ -h /etc/localtime ]]; then
                tz=$(readlink /etc/localtime | sed "s/\/usr\/share\/zoneinfo\///")
		echo "date.timezone = $tz" >> /etc/php.ini
		echo -e "Added timezone $tz to /etc/php.ini \n"
	else
	        echo -e "Automatic timezone detection failed, so you need to \n\
add a line like 'date.timezone = Europe/London' to /etc/php.ini\n\
See http://php.net/manual/en/timezones.php for the full list.\n\n\
Aborting zmsetup - Re-run it after fixing php timezone."
	        exit 1
	fi

fi
}

# Script main body starts here ================================
clear
# Check we are root
((UID)) && { echo "Sorry, you must run this as root."; exit 1; }
echo -e "*** Welcome to ZoneMinder Setup ***\nPlease wait a moment..."
# Get some data from zm.conf
get_cfg

# Check that mysql is installed and enabled
check_mysqld

# Stop apache mysql and zoneminder services
closeall

# Start mysql
systemctl start mysqld.service

# Check if a mysql root password is set and optionally set one
getpass

# Check for existing zm database and create new or update existing
chkdb

# Check timezone is set in php.ini
chkphp

# Start Apache and Zoneminder
systemctl start httpd.service > /dev/null 2>&1 || { echo "Problem starting Apache"; exit 1; }
systemctl start zoneminder.service || { echo "Problem starting ZoneMinder - look at /var/logs/zm/zm_pkg.log"; exit 1; }
# If we got this far then congratulations are in order!
echo -e "Congratulations - ZoneMinder is now running.\nYou should be able to \
access the ZM Console in your browser using :-\nhttp://$(hostname)/zm" 
