#!/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
NEW_HOSTNAME=$(cat $ROOT/etc/hostname)
xhost + local:""
sed -i s/ubuntu$/ubuntu\ $NEW_HOSTNAME/ /etc/hosts
mkdir -p $ROOT/tmp/.X11-unix
mount --bind /tmp/.X11-unix $ROOT/tmp/.X11-unix

#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 $NEW_HOSTNAME

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

#Run Mythtv-setup
xterm -e 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
chown 1000:1000 -R /home/$USER/.mythtv
SETUP
else
    cat <<SETUP >$ROOT/tmp/mythtv_setup
#!/bin/bash

#Set our new hostname
hostname $NEW_HOSTNAME

#Run Mythtv-setup
xterm -e 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
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
