#!/bin/bash

# settings
MYSQL=mysql

prefix=/usr/local
exec_prefix=${prefix}
bindir=${exec_prefix}/bin
datadir=${prefix}/share/verlihub
getdb=$bindir/vh_getdb
shell=/bin/bash
LD_RUNPATH=$LD_RUNPATH:${exec_prefix}/lib
timestamp=`date +%s`

if [ ! $PWD ]; then PWD=`pwd`; fi

if [ $USER == "root" ]; then
	default_cfgdir="/etc/verlihub"
	port_default=411
else
	default_cfgdir="$HOME/.verlihub"
	port_default=4111
fi

function die
{
	echo $1
	exit 1
}

function GetVar # ( command, default, question, response)
{
	if [ "_$1" == "_" ]; then
		d_val="$2" 
	else
		d_val=`$shell $1`||d_val="$2"
	fi
	read -p "$3"" ($d_val) " val
	[ "_$val" == "_" ] && val=$d_val
	#echo $4 |sed -e "s/%val%/$val/g" 1>&2
	echo $val
}

function YesNo # (question)
{
	read -p "$1"" (Y/N)" rep
	if [ "$rep" == "Y" ] || [ "$rep" == "y" ]; then
		return 0
	else
		return 1
	fi
}

function TestDB # (host, user, pass, database )
{
	$MYSQL -h "$1" -u "$2" -p"$3" -e "show databases" "$4" &>/dev/null  && return 0 || return 1
}

function Sep
{
	echo "--------------------------------"
}

function TestTables # (table1 table2 ...)
{
	while [ $1 ]; do
		$getdb --testtable "$1" || return 1
		shift
	done
	return 0
}

function getMySQLSocket
{
  MYSQL_CONF="/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf"
  for FILE in $MYSQL_CONF
    do
      if [ -r $FILE ]; then
        SOCKET=$(cat $FILE | grep "^socket" | head -n 1 | cut -d"=" -f2| tr -d " ")
        fi
        done
        
        
}

function CreateTables
{

	TestTables "reglist" "SetupList" && return 0
	echo Wait few seconds..
	getMySQLSocket
	export "MYSQL_UNIX_PORT=$SOCKET"
	VERLIHUB_CFG=$cfg_dir $bindir/verlihub 22 &>$cfg_dir/install_log &
	vh_pid=$!
	sleep 5
	kill -9 $vh_pid &>/dev/null
	TestTables "reglist" "SetupList" || return 1
	return 0
}

function PrintCfgFolderStatus # (folder)
{
	if [ $1 ] && [ -d $1 ]; then
		status=`ls -ld "$1"|cut -d\  -f 1`
	else
		status="-inexisting-"
	fi
	
	echo -n $1 $status
}


Sep
realname=`GetVar "" "$USER" "Your name ?" "Hi, %val%!!"`

echo
echo "Hello $realname, "
echo "let's start with configuration of database access.."
echo
Sep

db_info_ok=false

until $db_info_ok;
do
	mysql_data=`GetVar "$getdb --getdata" "verlihub" "mysql database for verlihub will be called?"`
	mysql_user=`GetVar "$getdb --getuser" "verlihub" "mysql user to access $mysql_data gonna be?"`
	mysql_pass=`GetVar "$getdb --getpass" "$timestamp" "password to access $mysql_data be?"`
	mysql_host=`GetVar "$getdb --gethost" "localhost" "mysql server will run where?"`
	
	Sep
	echo "user     = $mysql_user"
	echo "password = $mysql_pass"
	echo "host     = $mysql_host"
	echo "database = $mysql_data"
	Sep

	TestDB "$mysql_host" "$mysql_user" "$mysql_pass" "$mysql_data" && db_exists=true || db_exists=false
	$db_exists && echo "This database account exists" || echo "This database account cannot be accessed"
	Sep

	YesNo "Is this info correct ?" && db_info_ok=true || echo "Let's do it again"
done


db_create=false
if ! $db_exists; then
	YesNo "Do you want to create database now?" && db_create=true 
fi

if $db_create ; then
	Sep
	echo Ok preparing mysql..
	echo "You probably need administrator access to mysql database"

	mysql_root=`GetVar "" "root" "mysql administrator username?"`

	if [ $mysql_host != "localhost" ]; then
		mysql_this_host=`GetVar "hostname" "localhost" "Verlihub's server as host from the mysql's scope is?"`
	else
		mysql_this_host="localhost"
	fi;

	echo
	Sep
	echo

	echo "You'll be now promted by $MYSQL client for password of $mysql_root@$mysql_host"
	$MYSQL -h "$mysql_host" -u "$mysql_root" -p -e "CREATE DATABASE IF NOT EXISTS $mysql_data; GRANT ALL ON $mysql_data.* to $mysql_user@$mysql_this_host identified by '$mysql_pass'"
	Sep

	TestDB "$mysql_host" "$mysql_user" "$mysql_pass" "$mysql_data" && db_exists=true || db_exists=false
	$db_exists && echo "This database account exists" || echo "WARNING: This database account cannot be accessed, consider starting the $MYSQL server"
	Sep
fi;


echo
Sep
echo
echo "$realname, you need to choos a place for the configuration files"
Sep
echo "The order of folder that verlihub is looking for is following:"
echo 
echo -n "1 - variable \$VERLIHUB_CFG          - "; PrintCfgFolderStatus "$VERLIHUB_CFG"; echo
echo -n "2 - ./.verlihub                      - "; PrintCfgFolderStatus "$PWD/.verlihub"; echo
echo -n "3 - $HOME/.verlihub        - "; PrintCfgFolderStatus "$HOME/.verlihub"; echo
echo -n "4 - $prefix/etc/verlihub   - "; PrintCfgFolderStatus "$prefix/etc/verlihub"; echo
echo -n "5 - /etc/verlihub                    - "; PrintCfgFolderStatus "/etc/verlihub"; echo
echo "if two or more of these exist, lower number has priority"
Sep
echo


cfg_info_ok=false

until $cfg_info_ok;
do
	Sep
	cfg_dir=`GetVar "$bindir/vh_getcfg" "$default_cfgdir" "what is will be the configuration folder ?"`

	[ -d $cfg_dir ] && cfg_exists=true || cfg_exists=false
	$cfg_exists && echo "This config folder already exists and may be overwitten (with a backup)" || echo "The config folder $cfg_dir does not exist and would be created"
	Sep

	YesNo "Do you want to continue with these settings (if not then select another folder) ?" && cfg_info_ok=true || echo "Let's do it again"
done



cfg_create=true
if $cfg_exists; then
	YesNo "Do you want to overwrite the existing configuration ?" || cfg_create=false
fi

if $cfg_create ; then
	Sep
	mkdir -p $cfg_dir
	cfg_dbconfig="$cfg_dir/dbconfig"

	# backup eventually the original config
	if [ -e $cfg_dbconfig ]; then
		tmpdir=/tmp/vh_install_$$_$timestamp
		mkdir $tmpdir
		mv $cfg_dir/* $tmpdir
		mv $tmpdir $cfg_dir/_backup
		echo "FYI: original configuration has been moved to $cfg_dir/_backup"
	fi

	echo "db_host = $mysql_host" >  $cfg_dbconfig
	echo "db_data = $mysql_data" >> $cfg_dbconfig
	echo "db_user = $mysql_user" >> $cfg_dbconfig
	echo "db_pass = $mysql_pass" >> $cfg_dbconfig

	echo "Written: $cfg_dbconfig"

	cp -R ${prefix}/share/verlihub/config/* $cfg_dir
	mkdir -p $cfg_dir/plugins
	mkdir -p $cfg_dir/scripts
	ln -s ${exec_prefix}/lib/libplug_pi.so $cfg_dir/plugins
fi

echo
Sep
echo

[ -f $cfg_dbconfig ] && cfg_exists=true || cfg_exists=false

if ! $db_exists ||  ! $cfg_exists ; then
	echo "ERROR: Your installation is NOT complete"
	echo "Either you were unable to create database or config folder"
	echo "Without both valid I cannot continue"
	echo "Come back with necessary info, permissions and running $MYSQL server and run me again"
	exit 1
fi

export VERLIHUB_CFG=$cfg_dir

CreateTables || die "ERROR: verlihub's $MYSQL tables do not exist, cannot continue installation. Please check $cfg_dir/install_log file for more info";
	

Sep
echo "$realname, now I will ask you few more questions about your future hub, if you permit.."
echo


setup_info_ok=false

until $setup_info_ok; do
	Sep
	echo "Try to not put many special characters, you'll be able to put some later"
	echo
	hostname=`hostname`
	vh_master=`GetVar "" "[SU]$USER" "Give me your DC hub master nickname.."`
	vh_passwd=`GetVar "" "$timestamp" "Choose your password.."`
	vh_hubport=`GetVar "" "$port_default" "Which will be default ONE hub  port number?"`
	vh_hubhost=`GetVar "" "$hostname" "What will be your hub hostname?"`
	vh_hubname=`GetVar "" "hub of $realname" "Give me the name of your hub"`
	
	vh_master=`echo $vh_master | tr " |$" "___"`

	Sep
	echo "Hub: '$vh_hubname'"
	echo "url: 'dchub://$vh_hubhost:$vh_hubport'"
	echo "Master user: '$vh_master'"
	echo "Master's password: '$vh_passwd'"
	Sep

	YesNo "Is this info correct ?" && setup_info_ok=true || echo "Let's do it again"
done

echo "FYI: settings are going to be created or updated"

$bindir/vh_setup "hub_name" -f "config" -v "$vh_hubname"
$bindir/vh_setup "hub_host" -f "config" -v "$vh_hubhost:$vh_hubport"
$bindir/vh_setup "listen_port" -f "config" -v "$vh_hubport"

$bindir/vh_regnick -f -c 10 -n "$vh_master" -p "$vh_passwd"
$bindir/vh_getdb --script $datadir/sql/default_reglist.sql

echo "done"

exit 0

