#!/bin/bash

LOCKFILE="/root/vici-inst.lock"
FIRSTBOOT="/root/firstboot"
BASEURL="http://download.vicidial.com/ubuntu"
UPDATER="ubuntu-vici-updater-vicibox.sh"
UPURL="$BASEURL/$UPDATER"
INSTALLER="ubuntu-vici-installer-vicibox.sh"
INSTURL="$BASEURL/$INSTALLER"
SELFPATH="/etc/init.d/vici-inst"
RCPATH="/etc/rc2.d/S98vici-inst"
LOGPATH="/var/log/astguiclient"
LOGFILE="$LOGPATH/ubuntu-vici-install.log"
TMPDIR="/tmp/vici-inst"

. /lib/lsb/init-functions

do_install()
{
	mkdir -p $LOGPATH	# make the log directory
	# check if the lock file exists
	if [ -f $LOCKFILE ] ; then
		# if so
		if [ -f $FIRSTBOOT ] ; then
			mkdir -p $TMPDIR	# make the tmp directory to run the installer out of
			cd $TMPDIR		# got to the tmp directory
			wget $UPURL 2> $LOGFILE > $LOGFILE	# get the updater
			chmod +x $TMPDIR/$UPDATER		# make it executable
			$TMPDIR/$UPDATER	# run it
			rm $FIRSTBOOT		# remove the firstboot file
			shutdown -r now		# reboot the computer
		else
			mkdir -p $TMPDIR	# make the tmp directory to run the installer out of
			cd $TMPDIR		# got to the tmp directory
			wget $INSTURL 2> $LOGFILE > $LOGFILE	# get the installer
			chmod +x $TMPDIR/$INSTALLER		# make it executable
			$TMPDIR/$INSTALLER	# run it
			rm -Rf $TMPDIR		# remove the temp directory and everything in it
			rm $LOCKFILE		# remove the lock file
			rm $RCPATH		# remove the rc symlink
			rm $SELFPATH		# remove this initscript
			return 1
		fi
	else
		# if not return an error
		echo "Lockfile not found" >> $LOGFILE	
		return 2
	fi
}

case "$1" in
  start|install)
        log_daemon_msg "Starting Vicidial Installer" "vici-inst"
        do_install
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
  prepare)
	log_daemon_msg "Preparing Vicidial Installer" "vici-inst"
	touch $LOCKFILE
	touch $FIRSTBOOT
	if [ -f $RCPATH ] ; then
		echo "$RCPATH already exists"
	else
		ln -s $SELFPATH $RCPATH
	fi
        log_end_msg 0 
	;;
  *)
        echo "Usage: $SCRIPTNAME {start|install|prepare}" >&2
        exit 3
        ;;
esac
