#!/bin/sh
# Used to Launch MythTV-Setup & MySQL as needed
# Copyright © 2007  Mario Limonciello

#Let debconf work
. /usr/share/debconf/confmodule
db_get passwd/username
USER=$RET

ROOT="/target"
chroot=chroot
log='log-output -t mythbuntu'

mount -t proc none $ROOT/proc
mount -t devpts none $ROOT/dev/pts
mount -t sysfs sysfs $ROOT/sys
mount --bind /lib/modules/`uname -r`/volatile $ROOT/lib/modules/`uname -r`/volatile

#to run X apps in the chroot
xhost +
mkdir -p $ROOT/tmp/.X11-unix
mount --bind /tmp/.X11-unix $ROOT/tmp/.X11-unix
xauth extract - $DISPLAY > $ROOT/tmp/Xcookie
cat $ROOT/tmp/Xcookie | $chroot $ROOT xauth -f /root/.Xauthority merge -
cat $ROOT/tmp/Xcookie | $chroot $ROOT xauth merge -

#Prepare chroot script
db_get mythbuntu/install_type
TYPE="$RET"
if [ "$TYPE" = "Master Backend/Frontend" ] || [ "$TYPE" = "Master Backend" ]; then
    cat <<SETUP >$ROOT/tmp/mythtv_setup
#!/bin/bash

#Set our new hostname
hostname -F /etc/hostname

#Startup SQL
/etc/init.d/mysql start

#Run Mythtv-setup
mythtv-setup.real

#Fill Database
zenity --title "Fill Database?" --question --text "Would you like to run mythfilldatabase?"
DATABASE_NOT=\$?
if [ "\$DATABASE_NOT" = "0" ]; then
    xterm -title "Running mythfilldatabase" -e "unset DISPLAY && unset SESSION_MANAGER && mythfilldatabase; sleep 3"
fi

#Stop SQL
/etc/init.d/mysql stop

#Make sure warning doesn't come up on next boot
mkdir -p /home/$USER/.mythtv
touch /home/$USER/.mythtv/backend_configured
chown 1000:1000 -R /home/$USER/.mythtv
SETUP
else
    cat <<SETUP >$ROOT/tmp/mythtv_setup
#!/bin/bash

#Set our new hostname
hostname -F /etc/hostname

#Run Mythtv-setup
mythtv-setup.real

#Fill Database
zenity --title "Fill Database?" --question --text "Would you like to run mythfilldatabase?"
DATABASE_NOT=\$?
if [ "\$DATABASE_NOT" = "0" ]; then
    xterm -title "Running mythfilldatabase" -e "unset DISPLAY && unset SESSION_MANAGER && mythfilldatabase; sleep 3"
fi

#Make sure warning doesn't come up on next boot
mkdir -p /home/$USER/.mythtv
touch /home/$USER/.mythtv/backend_configured
chown 1000:1000 -R /home/$USER/.mythtv
SETUP
fi

#Launch chroot script
chmod +x $ROOT/tmp/mythtv_setup
$log $chroot $ROOT /tmp/mythtv_setup
rm $ROOT/tmp/mythtv_setup

#to clean up the whole procedure
umount $ROOT/proc
umount $ROOT/sys
umount $ROOT/dev/pts
umount $ROOT/tmp/.X11-unix
umount $ROOT/lib/modules/`uname -r`/volatile
