#!/bin/sh
# Mario Limonciello, April 2016

set -e

#source our dialog functions
. /usr/share/mythtv/dialog_functions.sh

#get database info
getXmlParam() {
  perl -e '
    use XML::Simple;
    use Data::Dumper;
    $xml = new XML::Simple;
    $data = $xml->XMLin("/etc/mythtv/config.xml");
    print "$data->{Database}->{$ARGV[0]}\n";
  ' -- "$1"
}
DBHost="$(getXmlParam Host)"
DBUserName="$(getXmlParam UserName)"
DBPassword="$(getXmlParam Password)"
DBName="$(getXmlParam DatabaseName)"

#get mythfilldatabase arguments
mbargs=$(mysql -N \
 --host="$DBHost" \
 --user="$DBUserName" \
 --password="$DBPassword" \
 "$DBName" \
 --execute="SELECT data FROM settings WHERE value = 'MythFillDatabaseArgs';" \
)

#find the session, dialog and su manager we will be using for display
find_session
find_dialog
find_su

xterm -title "MythTV Setup Terminal" -e taskset -c 0 /usr/bin/mythtv-setup.real --syslog local7 -w -geometry 800x600 "$@"
$SU_TYPE systemctl reset-failed mythtv-backend --message "Please enter your current login password to stop mythtv-backend."
$SU_TYPE systemctl start mythtv-backend  --message "Please enter your current login password to start mythtv-backend."
dialog_question "Fill Database?" "Would you like to run mythfilldatabase?"
DATABASE_NOT=$?
if [ "$DATABASE_NOT" = "0" ]; then
	xterm -title "Running mythfilldatabase" -e "unset DISPLAY && unset SESSION_MANAGER && mythfilldatabase $mbargs; sleep 3"
fi

#don't autorun again
rm -f /home/$USER/.config/autostart/initial-setup.desktop
rm -f /home/$USER/Desktop/initial-setup.desktop
rm -f /home/$USER/Desktop/setup-instructions.desktop

#autostart mythfrontend?
if which mythfrontend; then
	rm -f /home/$USER/.config/autostart/mythtv.desktop
	ln -s /usr/share/applications/mythtv.desktop /home/$USER/.config/autostart/mythtv.desktop
	mythfrontend --service
fi
