#!/bin/bash
# zmsetup
#
# Description:
# This is a basic setup tool for the Mageia installation of ZoneMinder.
# It assumes a default installation of mysql 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.
# When all is ready it will start Apache, and ZoneMinder.
#
# Use:-
# After installation of ZoneMinder run this script as root and answer any questions.
# $ su
# # zmsetup
#===================================
#Changelog
# 17/09/2013 Use zmuser not root to modify db
# 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
}

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 (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
echo "Updating database structure if 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 1
fi
fi

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

[[ $updt = 1 ]] && updtdb
}
#----------------------------
updtdb()
{
zmupdate.pl -u $zm_db_user -p $zm_db_pass -d /usr/share/zoneminder/db
}

# 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

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