#!/bin/sh

# ---------------------------------------------------------------------------------------
# Terminal colors
NORMAL='\033[0m'
#GOOD='\033[32;01m'
GOOD='\033[33;01m'
BAD='\033[31;01m'

# ---------------------------------------------------------------------------------------
msg() {
	echo -e "${GOOD}new.sh: ${NORMAL} $*"
}

# ---------------------------------------------------------------------------------------
msg_error() {
	echo -e "${BAD}new.sh Error: ${NORMAL} $*"
}

# ---------------------------------------------------------------------------------------

close_clock_apps() {
	msg "Preparing to stop processes..."
	msg "Stopping Clock Processes..."
	export update_memstick=1
	/usr/local/bin/stopclock
	msg "Stopping Clock Processes... (Double check)"
	sleep 1
	killall watchdog > /dev/null 2>&1
	killall rdate > /dev/null 2>&1
	killall csrdate > /dev/null 2>&1
	msg "Stopping Clock Processes... (Triple check)"
	sleep 1
	killall -9 watchdog > /dev/null 2>&1
	killall -9 host > /dev/null 2>&1
	killall -9 clockos > /dev/null 2>&1
	killall -9 pcserver > /dev/null 2>&1
	killall -9 replicate > /dev/null 2>&1
	killall -9 mcr > /dev/null 2>&1
	killall -9 php-cgi > /dev/null 2>&1
	killall -9 nfiq > /dev/null 2>&1
	killall -9 gsm > /dev/null 2>&1
	killall -9 sms > /dev/null 2>&1
	killall -9 dbbackup > /dev/null 2>&1
	msg "Listing Running Processes..."
	ps
}


# -----------------------------------------------------------------------------
# Automatically updated Version Numbers - do not edit (generated from build.sh)
# -----------------------------------------------------------------------------
CLOCK_BUILD_NUMBER=3010
CLOCK_VERSION=3.01

#CLOCK_MARK_III=3000

CA_CERT=/usr/local/share/trustedcerts/cacerts.crt
WGET_OPTIONS="-T 30 -t 3 --ca-certificate $CA_CERT"

#if grep UPDATE_TYPE=alpha /usr/local/bin/updateclock >/dev/null ; then 
#	msg_error "Changing default update type in old script to Release..."
#	sed -i 's/UPDATE_TYPE=alpha/UPDATE_TYPE=release/' /usr/local/bin/updateclock
#	msg_error "We will now attempt to run the update process again..."
#	exec /usr/local/bin/updateclock
# # Should not get here....
#	return 1
#fi	

#UPDATE_CONFIG=/var/local/data/update_type
# -----------------------------------------------------
# UPDATE_TYPE can be either: release, beta, or alpha
# -----------------------------------------------------
#if [ -s $UPDATE_CONFIG ]; then
#	. $UPDATE_CONFIG
#fi	
#UPDATE_TYPE=${UPDATE_TYPE-release}
UPDATE_TYPE_FILE="/var/local/data/update_type"
UPDATE_TYPE=$(cat $UPDATE_TYPE_FILE)

DOWNLOAD_FILE_NAME=new.tar.gz
# Need to change url e.g. clocks3 to clocks4 (change throughout file)
SECURE_DOWNLOAD_FILE=https://www.capefox.com/secure/clocks3/$UPDATE_TYPE/$DOWNLOAD_FILE_NAME

if [ "$1" = "--memstick" ]; then
	memstick=1
else 
	if [ "$2" = "--memstick" ]; then
		memstick=1
	else 
		memstick=0
	fi
fi

if [ "$1" = "--vartmp" ]; then
	vartmp=1
else 
	if [ "$2" = "--vartmp" ]; then
		vartmp=1
	else 
		vartmp=0
	fi
fi


if [ "$1" = "--force" ]; then
	force=1
else 
	if [ "$2" = "--force" ]; then
		force=1
	else 
		force=0
	fi
fi

if [ "$memstick" -eq 1 ]; then
	MEMSTICK_MOUNT_POINT=/mnt/1
	SECURE_DOWNLOAD_FILE=$MEMSTICK_MOUNT_POINT/$UPDATE_TYPE/$DOWNLOAD_FILE_NAME
	TEMP_UPDATES_DIR=/var/tmp/clock_updates
	NEW_FILE_VERSION=/var/local/updates/clock_update_new_version
else 
  if [ "$vartmp" -eq 1 ]; then
	  SECURE_DOWNLOAD_FILE=var/tmp/$UPDATE_TYPE/$DOWNLOAD_FILE_NAME
		TEMP_UPDATES_DIR=/var/tmp/$UPDATE_TYPE
		NEW_FILE_VERSION=/var/tmp/$UPDATE_TYPE/new.txt
	else
		SECURE_DOWNLOAD_FILE=https://www.capefox.com/secure/clocks3/$UPDATE_TYPE/$DOWNLOAD_FILE_NAME
		TEMP_UPDATES_DIR=/var/tmp/clock_updates
		NEW_FILE_VERSION=/var/local/updates/clock_update_new_version
	fi	
fi

TEMP_EXTRACT_DIR=$TEMP_UPDATES_DIR/extract
DOWNLOAD_FILE=$TEMP_UPDATES_DIR/$DOWNLOAD_FILE_NAME

DATABASE=/var/local/data/capeclock.db

# -----------------------------------------------------------------------------
# Startup
# -----------------------------------------------------------------------------
msg "Updating the Clock to Version $CLOCK_VERSION (Build $CLOCK_BUILD_NUMBER)"
msg "Update Type: $UPDATE_TYPE"

mkdir -p $TEMP_UPDATES_DIR
# -----------------------------------------------------------------------------
# download all the compressed files necessary to perform the update
# do not need to decompress the files.
# -----------------------------------------------------------------------------
if [ "$memstick" -eq 1 ]; then
	/usr/local/bin/mount_usb
  result=`mount | grep /mnt/1`
  if [ -n "$result" ];
  then
	  echo usb drive found
  else
    echo update failed usb drive not found
    exit 1 # fail
  fi	

	#mount -t vfat -o umask=0000 /dev/sda1 $MEMSTICK_MOUNT_POINT
	msg "Downloading File Updates from the Memory Stick..."
	cp -f $SECURE_DOWNLOAD_FILE $DOWNLOAD_FILE
else
	if [ "$vartmp" -eq 1 ]; then
		msg "File should already be in /var/tmp"
	else
		close_clock_apps
		msg "Downloading File Updates from the Web..."
		wget $WGET_OPTIONS -O $DOWNLOAD_FILE $SECURE_DOWNLOAD_FILE
	fi	
fi 
if [ $? -ne 0 ]; then         # Test exit status of wget command.
	msg_error "Could Not Download File Updates"
	rm -f $DOWNLOAD_FILE > /dev/null 2>&1
	exit 1
fi
chmod 0600 $DOWNLOAD_FILE
if [ "$memstick" -eq 1 ]; then
	umount $MEMSTICK_MOUNT_POINT > /dev/null 2>&1
fi
if [ ! -s  $DOWNLOAD_FILE ]; then         
	msg_error "Could Not Download File Updates"
	rm -f $DOWNLOAD_FILE > /dev/null 2>&1
	exit 1
fi

# -----------------------------------------------------------------------------
# Check hash - hey wow man....
# -----------------------------------------------------------------------------
sha_a=`sha1sum $DOWNLOAD_FILE`
sha_b=`sed -n "/$DOWNLOAD_FILE_NAME/s|$DOWNLOAD_FILE_NAME|$DOWNLOAD_FILE|p" $NEW_FILE_VERSION`
msg "Download: $sha_a"
msg "Orig    : $sha_b"
if [ "$sha_a" != "$sha_b" ]; then
	msg_error "The downloaded file ($DOWNLOAD_FILE) does not match the Check Sum!! The downloaded files will be deleted. Please try again later."
	rm -f $DOWNLOAD_FILE > /dev/null 2>&1
	rm -f $NEW_FILE_VERSION
	exit 1
fi 

# -----------------------------------------------------------------------------
# now all processes have to be terminated
# given a bit of time killing the watchdog should terminate all the other processes.
# -----------------------------------------------------------------------------
msg "Stopping Web Server in 10 seconds...."
sleep 10
msg "Stopping Web Server now"
/etc/init.d/lighttpd stop
msg "Stopping php"
killall php-cgi > /dev/null 2>&1

close_clock_apps
# Kill modem programs (must be restarted before watchdog)
/etc/init.d/pppcontrol stop
wait
/etc/init.d/muxcontrol stop
wait

# -----------------------------------------------------------------------------
# Delete any files that are now obsolete
# -----------------------------------------------------------------------------
msg "Removing Outdated Files..."
rm -f /var/local/www/myphours.php
if [ -e /home/thisishome ]; then
	echo This Is Home
else	
	rm -r /home
fi
rm /var/local/www/phpinfo.php
rm /var/sdcard/www/phpinfo.php
rm /var/local/www/admin.html
rm /var/sdcard/www/admin.html
rm /usr/local/bin/usbrun.sh

# -----------------------------------------------------------------------------
# Uncompress file, part 1
# -----------------------------------------------------------------------------
msg "Getting Ready to Extract Update Files..."
rm -rf $TEMP_EXTRACT_DIR
mkdir -p $TEMP_EXTRACT_DIR
msg "Extracting Update Files..."
tar -xvzf $DOWNLOAD_FILE -C $TEMP_EXTRACT_DIR var/local
if [ $? -ne 0 ]; then
	msg_error "Extracting $DOWNLOAD_FILE failed."
	exit 1
fi
msg "Extracting Update Files - Done"
#rm -f $DOWNLOAD_FILE


# -----------------------------------------------------------------------------
# Copy files part 1
# -----------------------------------------------------------------------------

msg "Updating /var/local/ from $TEMP_EXTRACT_DIR/var/local"
msg "cp -rf $TEMP_EXTRACT_DIR/var/local/* /var/local/"
cp -rfp $TEMP_EXTRACT_DIR/var/local/* /var/local/
#if [ $? -ne 0 ]; then         
#	msg_error "Updating /var/local/ ... failed."
#	exit 1
#fi
cp -rfp $TEMP_EXTRACT_DIR/var/local/* /var/sdcard/
#exit 0 # debugging remove me

# -----------------------------------------------------------------------------
# Uncompress file, part 2
# -----------------------------------------------------------------------------
msg "Getting Ready to Extract Update Files..."
rm -rf $TEMP_EXTRACT_DIR
mkdir -p $TEMP_EXTRACT_DIR
msg "Extracting Update Files..."
tar -xvzf $DOWNLOAD_FILE -C $TEMP_EXTRACT_DIR usr/local
if [ $? -ne 0 ]; then         
	msg_error "Extracting $DOWNLOAD_FILE failed."
	exit 1
fi
msg "Extracting Update Files - Done"
#rm -f $DOWNLOAD_FILE

# -----------------------------------------------------------------------------
# Copy files part 2
# -----------------------------------------------------------------------------

msg "Updating /usr/local/ ... (takes several minutes) ..."
cp -rf $TEMP_EXTRACT_DIR/usr/local/* /usr/local/
if [ $? -ne 0 ]; then         
	msg_error "Updating /usr/local/ ... failed."
	exit 1
fi

# -----------------------------------------------------------------------------
# Uncompress file, part 3
# -----------------------------------------------------------------------------
msg "Getting Ready to Extract Update Files..."
rm -rf $TEMP_EXTRACT_DIR
mkdir -p $TEMP_EXTRACT_DIR
msg "Extracting Update Files..."
 tar -xvzf $DOWNLOAD_FILE -C $TEMP_EXTRACT_DIR etc 
 if [ $? -ne 0 ]; then         
	msg_error "Extracting $DOWNLOAD_FILE failed."
	exit 1
 fi
msg "Extracting Update Files - Done"
#rm -f $DOWNLOAD_FILE

# -----------------------------------------------------------------------------
# Copy files part 3
# -----------------------------------------------------------------------------

msg "Updating /etc/ ..."
# Don't copy wpa_supplicant.conf if it already exists.
if [ -e /etc/wpa_supplicant.conf ]
then
	rm $TEMP_EXTRACT_DIR/etc/wpa_supplicant.conf
fi
cp -rf $TEMP_EXTRACT_DIR/etc/* /etc/
 if [ $? -ne 0 ]; then         
 	msg_error "Updating /etc/ ... failed."
 	exit 1
 fi

# -----------------------------------------------------------------------------
# Uncompress file, part 4
# -----------------------------------------------------------------------------
#msg "Getting Ready to Extract Update Files..."
#rm -rf $TEMP_EXTRACT_DIR
#mkdir -p $TEMP_EXTRACT_DIR
#msg "Extracting Update Files..."
# tar -xvzf $DOWNLOAD_FILE -C $TEMP_EXTRACT_DIR lib/firmware 
# if [ $? -ne 0 ]; then         
#	msg_error "Extracting $DOWNLOAD_FILE failed."
#	exit 1
# fi
#msg "Extracting Update Files - Done"
#rm -f $DOWNLOAD_FILE

# -----------------------------------------------------------------------------
# Copy files part 4
# -----------------------------------------------------------------------------

#msg "Updating /etc/ ..."
#cp -rf $TEMP_EXTRACT_DIR/lib/firmware/* /lib/firmware/
# if [ $? -ne 0 ]; then         
# 	msg_error "Updating /lib/firmware/ ... failed."
# 	exit 1
# fi

# -----------------------------------------------------------------------------
# Do extra bits and pieces
# -----------------------------------------------------------------------------
msg "Configuring bits and pieces ..."
chmod 4755 /bin/date
chmod 0777 /usr/local/bin/adjustscripts.sh
chmod 0777 /usr/local/bin/autobackup.sh
chmod 0777 /usr/local/bin/autostop
chmod 0777 /usr/local/bin/csapi.sh
chmod 0777 /usr/local/bin/csrdate
chmod 0777 /usr/local/bin/dbbackup
chmod 0777 /usr/local/bin/email.sh
chmod 0777 /usr/local/bin/gsm
chmod 0777 /usr/local/bin/gsmcheck.sh
chmod 0777 /usr/local/bin/gsmserial
chmod 0777 /usr/local/bin/ipnhrly
chmod 0777 /usr/local/bin/ipnotify
chmod 0777 /usr/local/bin/mac.sh
chmod 0777 /usr/local/bin/mconf
chmod 0777 /usr/local/bin/mcr
chmod 0777 /usr/local/bin/nfiq
chmod 0777 /usr/local/bin/nfiq.sh
chmod 0777 /usr/local/bin/nfiqwsq.sh
chmod 0777 /usr/local/bin/pppcheck.sh
chmod 0777 /usr/local/bin/pppcontrol
chmod 0777 /usr/local/bin/replay.sh
chmod 0777 /usr/local/bin/resetserial.sh
chmod 0777 /usr/local/bin/rollpass
chmod 0777 /usr/local/bin/setup.sh
chmod 0777 /usr/local/bin/sms
chmod 0777 /usr/local/bin/updateipnotifyc.sh
chmod 0777 /usr/local/bin/usbsetwifi.sh
chmod 0777 /usr/local/bin/wificheck.sh
chmod 0777 /usr/local/bin/wifi_setup.sh
chmod 0777 /usr/local/bin/wifiroute.sh
chmod 0444 /etc/cron.d/ipnotifyc
chmod 0444 /etc/cron.d/rollpassc
chmod 0777 /etc/init.d/checkusbupdate
chmod 0777 /etc/init.d/muxcontrol
chmod 0777 /etc/init.d/pppcontrol
chmod 0777 /etc/lighttpd
chmod 0666 /etc/lighttpd/lighttpd.conf
chmod 0777 /etc/network/if-up.d/0010sendwhoami
chmod 0777 /etc/ppp/ip-pre-up
chmod 0777 /etc/ppp/ip-down
chmod 0777 /etc/ppp/ip-up
chmod 0622 /etc/ppp/options
chmod 0777 /etc/ppp/ip-down.d/0005logpppdown
chmod 0777 /etc/ppp/ip-up.d/0005logpppup
chmod 0777 /etc/ppp/ip-up.d/0010sendwhoami

chmod 0622 /etc/ppp/peers/provider
chmod 0644 /etc/wpa_supplicant.conf
chmod 0777 /var/local/www/webupdate.sh

update-rc.d muxcontrol defaults
update-rc.d pppcontrol defaults
update-rc.d welcome start 1 2 3 4 5 .
update-rc.d clock defaults
update-rc.d checkusbupdate start 1 2 3 4 5 .

#set boot setting on mark 2 clocks
#sed -i 's/FSCKFIX=no/FSCKFIX=yes/' /etc/default/rcS

# -----------------------------------------------------------------------------
# Install wpa_supplicant for wifi
# -----------------------------------------------------------------------------
#/usr/bin/apt-get update
#/usr/bin/apt-get -y install wpasupplicant


# -----------------------------------------------------------------------------
# Install Any New Libraries
# -----------------------------------------------------------------------------
msg "Configuring  Libraries ..."

ln -sf libpro.so.1.0 /usr/local/lib/libpro.so
ln -sf libpro.so.1.0 /usr/local/lib/libpro.so.1

ln -sf libseq.so.1.0 /usr/local/lib/libseq.so
ln -sf libseq.so.1.0 /usr/local/lib/libseq.so.1

ln -sf libcam.so.1.0 /usr/local/lib/libcam.so
ln -sf libcam.so.1.0 /usr/local/lib/libcam.so.1

ln -sf libfpsu.so.1.0 /usr/local/lib/libfpsu.so
ln -sf libfpsu.so.1.0 /usr/local/lib/libfpsu.so.1

ln -sf libchild.so.1.0 /usr/local/lib/libchild.so
ln -sf libchild.so.1.0 /usr/local/lib/libchild.so.1

ln -sf libgsm.so.1.0 /usr/local/lib/libgsm.so
ln -sf libgsm.so.1.0 /usr/local/lib/libgsm.so.1

ln -sf libtools.so.1.0 /usr/local/lib/libtools.so
ln -sf libtools.so.1.0 /usr/local/lib/libtools.so.1

ldconfig

# -----------------------------------------------------------------------------
# Modify files
# -----------------------------------------------------------------------------
# msg "Modifying Network Files"
# sed -i 's|^DHCP_CLIENT="/sbin/udhcpc -i eth0"|DHCP_CLIENT="/sbin/udhcpc -i eth0  -H $(hostname) -s /usr/local/share/udhcpc/default.script"|' /etc/conf.d/net.eth0
msg "Modifying lftp.conf File"
DONE=$(grep "## Limiting options (SK)" /etc/lftp.conf | wc -l)
if [ $DONE -eq 0 ]
then
	echo "## Limiting options (SK)"
	echo "# No retries"
	echo "set net:max-retries 1"
	echo "# Network timeout"
	echo "set net:timeout 5m"
	echo "# Abort on disk full error"
	echo "set xfer:disk-full-fatal true"
fi

# -----------------------------------------------------------------------------
# run any database update scripts
# -----------------------------------------------------------------------------
msg "Updating Database... (You can safely ignore primary key and duplicate column errors) ..."
if [ -s /var/local/data/alter.sql ]; then
	/usr/local/bin/sqlite3shell $DATABASE < /var/local/data/alter.sql
	/usr/local/bin/sqlite3shell $DATABASE "drop index if exists menucat_catkey;"
	/usr/local/bin/sqlite3shell $DATABASE "create unique index if not exists menucat_catkey on menucat(language,model,catno);"
	/usr/local/bin/sqlite3shell $DATABASE "drop index if exists menuitem_catitemkey;"
	/usr/local/bin/sqlite3shell $DATABASE "create unique index if not exists menuitem_catitemkey on menuitem(language,model,catno,itemno);"
fi	

# -----------------------------------------------------------------------------
# update lighttpd so logs are sent to /var/tmp
# also (first) turn off access logging completely.
sed -i 's|^[ ]*"mod_accesslog",|#  "mod_accesslog",|' /etc/lighttpd/lighttpd.conf
sed -i 's|server.errorlog.*$|server.errorlog = "/var/tmp/weberror.log"|' /etc/lighttpd/lighttpd.conf
sed -i 's|accesslog.filename.*$|accesslog.filename = "/var/tmp/webaccess.log"|' /etc/lighttpd/lighttpd.conf
sed -i 's|compress.cache-dir.*$|compress.cache-dir = "/var/tmp/"|' /etc/lighttpd/lighttpd.conf
sed -i 's|;session.save_path = /var/lib/php5|session.save_path = /var/tmp|' /etc/php5/cgi/php.ini 
sed -i 's|max_execution_time.*$|max_execution_time = 180|' /etc/php5/cgi/php.ini
# -----------------------------------------------------------------------------

# Disable samba master browser
sed -i 's/^#[ ]*domain master = auto/domain master = no\nlocal master = no\npreferred master = no\nos level = 0\n/' /etc/samba/smb.conf

# -----------------------------------------------------------------------------
# Disable the ipnotifyc for clocks that use a modem
# -----------------------------------------------------------------------------
MINUTES=$(/usr/local/bin/sqlite3shell /var/local/data/capeclock.db "select whoamiminutes from thisdev;")
if [ "$MODEM" -eq 1 ] && [ "$MINUTES" -eq 61 ]
	then
	/usr/local/bin/sqlite3shell /var/local/data/capeclock.db 'update thisdev set whoamiminutes = 0 where id = 1;'
	echo "Disabling ipnotifyc for modem clocks" > /dev/kmsg
fi

# Set up ipnotifyc
/usr/local/bin/updateipnotifyc.sh

# set scripts for time clock or job clock
DEFAULTMODEL=$(/usr/local/bin/sqlite3shell $DATABASE "select defaultmodel from thisdev;")
if [ $DEFAULTMODEL -eq 6 ] # default model of 6 == job clock
then
	/usr/local/bin/adjustscripts.sh 1
else
	/usr/local/bin/adjustscripts.sh 0
fi


# -----------------------------------------------------------------------------
# End
# -----------------------------------------------------------------------------
msg "The End."

# exit 10 (or higher) will tell updateclock this was successful and that we need to reboot the clock
exit 10
