#!/bin/sh

echo Detect Large Flash Storage /etc/init.d/boottime/detectbigflash.sh > /var/tmp/dbf.log
# ---------------------------------------------------------------------------------------
# Terminal colors
NORMAL='\033[0m'
GOOD='\033[32;01m'
WARN='\033[33;01m'
BAD='\033[31;01m'
BRACKET='\033[34;01m'

#
MNTFLASH='/var/sdcard'
USBFLASH='/mnt/3/local'
USBDRIVE1='/mnt/3'
USBDRIVE2='/mnt/4'
USBDRIVE3='/mnt/5'
USBDRIVE4='/mnt/6'
MNTLOG='/var/sdcardlog'
USBLOG='/mnt/5'
USELOG='/var/sqllog'

# Terminal cursor positions.
# It's tempting to use absolute column positions (Esc [ n G sequences), but
# some terminal emulators can't handle them so let's use newline followed by
# relative up and right movement instead.
OKPOS='\n\033[2A\033[72C'
FAILPOS='\n\033[2A\033[71C'
INFOPOS='\n\033[A\033[4C'
# ---------------------------------------------------------------------------------------
information() {
	echo -e "${INFOPOS}${GOOD}+${NORMAL} $*"
}
# ---------------------------------------------------------------------------------------
begin() {
	echo -e " ${GOOD}*${NORMAL} $*... "
}
# ----------------------------------------------------------------------end does not exit.
end() {
	if [ "$1" = 0 ]; then
		echo -e "${OKPOS}${BRACKET}[ ${GOOD}ok${BRACKET} ]${NORMAL}"
	else
		shift
		if [ -n "$1" ]; then
			echo -e "${INFOPOS}${BAD}!${NORMAL} $*"
		fi
		echo -e "${FAILPOS}${BRACKET}[ ${BAD}fail${BRACKET} ]${NORMAL}"
	fi
}
# A---------------------------------------------------------------------------------------
propogate_diskat(){
	if [ "$DISKAT1" = "/dev/sda1" ];
	then
		DISKAT2="/dev/sda2"
		DISKAT3="/dev/sda3"
		DISKAT4="/dev/sda4"
	else
		if [ "$DISKAT1" = "/dev/sdb1" ];
		then
			DISKAT2="/dev/sdb2"
			DISKAT3="/dev/sdb3"
			DISKAT4="/dev/sdb4"
		fi	
	fi
}
# A---------------------------------------------------------------------------------------
format(){
  /usr/local/bin/sendchild "Starting Clock" "Formatting" $DISKAT1 ""
  echo formatting usb drive $STORAGEAT :: $DISKAT1 
	result=` mount | grep $USBDRIVE1`
	if [ -n "$result" ];
	then
		umount $USBDRIVE1 
	fi	
	result=` mount | grep $USBDRIVE2`
	if [ -n "$result" ];
	then
		umount $USBDRIVE2 
	fi	
	result=` mount | grep $USBDRIVE3`
	if [ -n "$result" ];
	then
		umount $USBDRIVE3 
	fi		
	result=` mount | grep $USBDRIVE4`
	if [ -n "$result" ];
	then
		umount $USBDRIVE4 
	fi		
	fdisk $STORAGEAT < /usr/local/bin/sda.in 
	propogate_diskat
	mke2fs -t ext4 $DISKAT1 
	mke2fs -t ext4 $DISKAT2
	mke2fs -t ext4 $DISKAT3
	mke2fs -t ext4 $DISKAT4
	sync
	mount_data
	if [ "$?" -eq "0" ];
	then
		cp /usr/local/bin/sda.in $USBDRIVE1/CSTimeClockFixedStorage_DNR 
		if [ "$?" -eq "0" ];
		then
			sync
			return 0
		else
			return 1
		fi
	else
		return 2
	fi	
}
# ---------------------------------------------------------------------------------------
set_mnt_flash_link(){
	information "remapping var/local, using $MNTFLASH, remapping $USELOG using $MNTLOG" 
	if [ -L /var/local ];
	then
		rm /var/local 
	fi	
	ln -s $MNTFLASH /var/local 
	chmod -R a+rwx /var/local/* 

	if [ -L $USELOG ];
	then
		rm $USELOG
	fi	
	if [ ! -d $MNTLOG ]; then
		mkdir $MNTLOG
	fi	
	ln -s $MNTLOG $USELOG 
	chmod -R a+rwx $USELOG/* 
	sync
}
# ---------------------------------------------------------------------------------------
set_usb_flash_link(){
	information "remapping var/local, using $USBFLASH" 
	if [ -L /var/local ];
	then
		rm /var/local 
	fi	
	ln -s $USBFLASH /var/local 
	chmod -R a+rwx /var/local/* 
	
  information "remapping $USELOG using $USBLOG"	
	if [ -L $USELOG ];
	then
		rm $USELOG
	fi	
	ln -s $USBLOG $USELOG 
	chmod -R a+rwx $USELOG/* 
	sync
}
# ---------------------------------------------------------------------------------------
copy_to_mnt_flash(){
	begin "Copying data from $USBFLASH to $MNTFLASH" 
  # move data files back to normal folder here, and set database to rw mode.
	cp -a $USBFLASH/* $MNTFLASH
	if [ "$?" -eq "0" ]; 
	then
		set_mnt_flash_link
		end 0
		return 0
	else
		end 1
		return 1
	fi	
}
# ---------------------------------------------------------------------------------------
copy_to_usb_flash(){
  # move data files to usb flash, and remap flash folder
	begin "Copying data from $MNTFLASH to $USBFLASH" 
	if [ ! -d $USBFLASH ];
	then
		mkdir $USBFLASH
	fi	
	cp -a $MNTFLASH/* $USBFLASH
	if [ "$?" -eq "0" ]; 
	then
		set_usb_flash_link
		end 0
		return 0
	else
		end 1
		return 1
	fi
}
# ---------------------------------------------------------------------------------------
copy_to_usb1_flash(){
  # move data files to other usb flash, and remap flash folder
	if [ ! -d /mnt/1/templocal ];
	then
		mkdir /mnt/1/templocal
	fi	
	cp -a $USBFLASH/* /mnt/1/templocal 
	if [ "$?" -eq "0" ]; 
	then
		sync
		return 0
	else
    return 1
	fi
}
# ---------------------------------------------------------------------------------------
copy_from_usb1_flash(){
  # move data files to usb flash, and remap flash folder
	if [ ! -d $USBFLASH ];
	then
		mkdir $USBFLASH 
	fi	
	cp -a /mnt/1/templocal/* $USBFLASH 
	if [ "$?" -eq "0" ]; 
	then
		set_usb_flash_link
		return 0
	else
    return 1
	fi
}
# ---------------------------------------------------------------------------------------
testcopy(){




























  return 0
}	
# B---------------------------------------------------------------------------------------
move_data_to_flash(){
	testcopy
	if [ "$?" -eq "0" ]; 
	then
		copy_to_mnt_flash
		if [ "$?" -eq "0" ]; 
		then
			return 0
		fi		
	fi
	return 1
}
# B---------------------------------------------------------------------------------------
make_sure(){
  if [ "$1" = "using_mnt_flash" ];
	then
		if [ -e /usr/local/bin/using_mnt_flash ];
		then
			return 0
		fi
		if [ -e /usr/local/bin/using_usb_flash ];
		then
			mv /usr/local/bin/using_usb_flash /usr/local/bin/using_mnt_flash
			sync
			return 0
		fi
		if [ -e /usr/local/bin/switch_to_mnt_flash ];
		then
			mv /usr/local/bin/switch_to_mnt_flash /usr/local/bin/using_mnt_flash
			sync
			return 0
		fi
		if [ -e /usr/local/bin/switch_to_usb_flash ];
		then
			mv /usr/local/bin/switch_to_usb_flash /usr/local/bin/using_mnt_flash
			sync
			return 0
		fi
		cp /usr/local/bin/setip.sh /usr/local/bin/using_mnt_flash 
		sync
	fi
  if [ "$1" = "using_usb_flash" ];
	then
		if [ -e /usr/local/bin/using_usb_flash ];
		then
			return 0
		fi
		if [ -e /usr/local/bin/using_mnt_flash ];
		then
			mv /usr/local/bin/using_mnt_flash /usr/local/bin/using_usb_flash
			sync
			return 0
		fi
		if [ -e /usr/local/bin/switch_to_mnt_flash ];
		then
			mv /usr/local/bin/switch_to_mnt_flash /usr/local/bin/using_usb_flash
			sync
			return 0
		fi
		if [ -e /usr/local/bin/switch_to_usb_flash ];
		then
			mv /usr/local/bin/switch_to_usb_flash /usr/local/bin/using_usb_flash
			sync
			return 0
		fi
		cp /usr/local/bin/setip.sh /usr/local/bin/using_usb_flash 
		sync
	fi
	return 0
}
# B---------------------------------------------------------------------------------------
switch_drive() {
	# does 	using_mnt_flash exist?
  if [ -e /usr/local/bin/using_mnt_flash ];
	then
		begin "Using $MNTFLASH for storage"
		set_mnt_flash_link
		end 0
		return 0 # success
	fi	

	# does using_usb_flash exist
  if [ -e /usr/local/bin/using_usb_flash ];
	then
	  if [ -e $USBFLASH/data/update_type ];
		then
			begin "Using $USBFLASH for storage"
      set_usb_flash_link
			end 0
		  return 0 # success
	  else
		  # thinks it's using usb flash, but really it's not as there's no $USBFLASH/local/data on flash disk
			begin "Data on $USBFLASH missing, switching to $MNTFLASH"
			mv /usr/local/bin/using_usb_flash /usr/local/bin/using_mnt_flash 
			set_mnt_flash_link
			end 0
	  	return 0 # success
    fi	
	fi	
  # has the "switch to mnt flash" setting been set?
  if [ -e /usr/local/bin/switch_to_mnt_flash ];
	then
		information "Switching to $MNTFLASH for storage"
		if [ -e $USBFLASH/data/capeclock.db ];
			then
			move_data_to_flash
			if [ "$?" -eq "0" ]; 
			then
				begin "Switch successful, storage on $MNTFLASH used"
				mv /usr/local/bin/switch_to_mnt_flash /usr/local/bin/using_mnt_flash # switch worked
				sync
				end 0
			else
				begin "Switch unsuccessful, storage on $USBFLASH used"
				mv /usr/local/bin/switch_to_mnt_flash /usr/local/bin/using_usb_flash # switch failed
				sync
				end 0
			fi	
			return 0
		else
			begin "No data on $USBFLASH, storage on $MNTFLASH used"
			mv /usr/local/bin/switch_to_mnt_flash /usr/local/bin/using_mnt_flash # switch kinda worked
			sync
			end 0
		fi		
	fi

	# has the "switch to usb" setting been set?
  if [ -e /usr/local/bin/switch_to_usb_flash ];
	then
		information "Switching to $USBFLASH for storage"
		copy_to_usb_flash
		if [ "$?" -eq "0" ]; 
		then
			begin "Switch successful, storage on $USBFLASH used"
			mv /usr/local/bin/switch_to_usb_flash /usr/local/bin/using_usb_flash # switch worked
			sync
			end 0
		else
			begin "Switch unsuccessful, storage on $MNTFLASH used"
			mv /usr/local/bin/switch_to_usb_flash /usr/local/bin/using_mnt_flash # switch failed
			sync
			end 0
		fi	
		return 0
  fi
}
# A---------------------------------------------------------------------------------------
find_win95 (){
  begin "Checking for data on : mount -t $1 $2 $3 /dev/sda1 $USBDRIVE1" 
	mount -t $1 $2 $3 /dev/sda1 $USBDRIVE1 
	if [ "$?" -eq "0" ]; 
	then
		if [ -e $USBDRIVE1/CSTimeClockFixedStorage_DNR ];
		then
			STORAGEAT="/dev/sda"
			DISKAT1="/dev/sda1"
			end 0
			return 0
		else
			end 1
			information "Drive mounted ok, but CSTimeClockFixedStorage_DNR not found"
			result=`mount | grep $USBDRIVE1`
			if [ -n "$result" ];
			then
				umount $USBDRIVE1
			fi	
		fi	
	fi
	begin "Checking for data on : mount -t $1 $2 $3 /dev/sdb1 $USBDRIVE1" 
	mount -t $1 $2 $3 /dev/sdb1 $USBDRIVE1  
	if [ "$?" -eq "0" ]; 
	then
		if [ -e $USBDRIVE1/CSTimeClockFixedStorage_DNR ];
		then
			STORAGEAT="/dev/sdb"
			DISKAT1="/dev/sdb1"
			end 0
			return 0
		else
			end 1
			information "Drive mounted ok, but CSTimeClockFixedStorage_DNR not found"
			result=`mount | grep $USBDRIVE1`
			if [ -n "$result" ];
			then
				umount $USBDRIVE1
			fi	
		fi
	fi	
	return 1
}	
# A---------------------------------------------------------------------------------------
# try and change the formatting of the usb drive. Usually from Fat 32 or single partition ext2
change_format(){
  if [ -e /usr/local/bin/using_mnt_flash -o -e /usr/local/bin/using_usb_flash -o -e /usr/local/bin/switch_to_mnt_flash -o -e /usr/local/bin/switch_to_usb_flash];
	then
	  information "Using File Found"
	else
	  information "Created Using file"
		cp /usr/local/bin/setip.sh /usr/local/bin/using_mnt_flash 
		sync	
	fi
  if [ -e /usr/local/bin/using_mnt_flash ];
	then
	  # using mnt/flash at the moment, so safe to reformat STORAGEAT
		information "change format ok as using_mnt_flash detected"
		format
		if [ "$?" -eq "0" ];
		then 
			information "commence auto-switching to $USBFLASH"
			mv /usr/local/bin/using_mnt_flash /usr/local/bin/switch_to_usb_flash 
			sync
			return 0 # drive ready for switch
		else
      information "Attempted format of usb drive failed"
			return 1 # failed, stay on mnt/flash
		fi
  fi
  if [ -e /usr/local/bin/switch_to_usb_flash ];
	then
	  # using mnt/flash at the moment, so safe to reformat STORAGEAT
		information "change format as switch_to_usb_flash detected"
		format
		if [ "$?" -eq "0" ];
		then 
			information "commence switching to $USBFLASH"
			return 0 # drive ready for switch
		else
			information "Attempted format of usb drive failed"
			mv /usr/local/bin/switch_to_usb_flash /usr/local/bin/using_mnt_flash # drive not ready for switch
			sync
			return 1 # stay on mnt/flash
		fi
  fi	
	# now it gets tricky, because data is already on flash
  if [ -e /usr/local/bin/using_usb_flash -o -e /usr/local/bin/switch_to_mnt_flash]; 
	then
		information "change format as using_usb_flash detected"
		if [ -e $USBFLASH/data/capeclock.db ];
		then
			# using usb/flash at the moment, so try copy data file to mnt_flash. 
			testcopy
			if [ "$?" -eq "0" ];
			then		
				copy_to_mnt_flash
				if [ "$?" -eq "0" ]; 
				then
					mv /usr/local/bin/using_usb_flash /usr/local/bin/using_mnt_flash 
					sync
					format
					if [ "$?" -eq "0" ];
					then
						copy_to_usb_flash
						if [ "$?" -eq "0" ];
						then
							mv /usr/local/bin/using_mnt_flash /usr/local/bin/using_usb_flash 
							sync
							return 0 # success, data still on flash drive
						else
							return 1 # data ok, on mnt/flash (copy failed)
						fi	
					else
						return 1 # data ok, on mnt/flash (format failed)
					fi	
				else
					return 2 # data still on usb flash, copy to mnt failed. BUT possible $MNTFLASH is now 100% full.
				fi	
			else	
				# not enough space to copy database back onto mount drive
				# work in progress, for now do nothing
				return 2 # data still on usb flash,
			fi
		else
		  # clock says it's using usb flash, but there's no data there, so safe to format
			information "change format as using_usb_flash detected, but no data on drive"
			mv /usr/local/bin/using_usb_flash /usr/local/bin/using_mnt_flash 
			sync
			format
			if [ "$?" -eq "0" ];
			then
				mv /usr/local/bin/using_mnt_flash /usr/local/bin/switch_to_usb_flash 
				sync
				return 0 # ready to switch
			else
				return 1 # stay on mnt/flash
			fi	
		fi
  fi
	if [ -e $USBFLASH/data/capeclock.db ];
	then
		return 0
	else
		# no data on flash drive (and no indication in /usr/local/bin folder). So safe to format.
		information "change format as using_usb_flash detected, but no data on drive"
		cp /usr/local/bin/setip.sh /usr/local/bin/using_mnt_flash
		sync
		format
		if [ "$?" -eq "0" ];
		then
			mv /usr/local/bin/using_mnt_flash /usr/local/bin/switch_to_usb_flash 
			sync
			return 0 # ready to switch
		else
			return 1 # stay on mnt/flash
		fi	
	fi
}
# A---------------------------------------------------------------------------------------
mount_data(){
  mount -t ext4 $DISKAT1 $USBDRIVE1 
  mount -t ext4 $DISKAT2 $USBDRIVE2  
  mount -t ext4 $DISKAT3 $USBDRIVE3  
  mount -t ext4 $DISKAT4 $USBDRIVE4  
}
# A---------------------------------------------------------------------------------------
try_superblock(){
	e2fsck -y -b $2 $1
	if [ "$?" -eq "0" ]; then
		end 0
		/usr/local/bin/sendchild "Starting Clock" "" "" ""
		return 0
	fi
	if [ "$?" -eq "1" ]; then # errors corrected
		end 0
		/usr/local/bin/sendchild "Starting Clock" "" "" ""		
		return 0
	fi
	if [ "$?" -eq "2" ]; then # errors corrected, reboot required
	  end 0 
		/usr/local/bin/sendchild "Rebooting Clock" "" "" ""		
		reboot
		return 0
	fi	
}
# A---------------------------------------------------------------------------------------
check_disk(){
  /usr/local/bin/sendchild "Starting Clock" "Checking Data" "" ""
  begin "Check USB Drive Integrity -p"
	e2fsck -p $1
	if [ "$?" -eq "0" ]; 
	then
	  end 0
		return 0
	else
	  end 0 
		begin "Check USB Drive Integrity -y"
		e2fsck -y $1
		if [ "$?" -eq "0" ]; 
		then
			end 0
			return 0
		else	
			if [ "$?" -eq "1" ]; 
			then
				end 0
				return 0
			else
				echo all yours bruce $?
				/usr/local/bin/sendchild "Starting Clock" "Problem 7 Detected" "Contact Support" "" 
				end 1
				return 1
			fi	
		fi	
	fi
	/usr/local/bin/sendchild "Starting Clock" "" "" ""
}
# ---------------------------------------------------------------------------------------
linux_find(){
	STORAGEAT=""
	result=`fdisk -l | grep Linux | grep /dev/sda1`
	if [ -n "$result" ];
	then
		STORAGEAT="/dev/sda"
		DISKAT1="/dev/sda1"
		result=`fdisk -l | grep Linux | grep /dev/sda2`
		if [ -n "$result" ];
		then
		  DISKAT2="/dev/sda2"
			DISKAT3="/dev/sda3"
			DISKAT4="/dev/sda4"
		fi
	else
		result=`fdisk -l | grep Linux | grep /dev/sdb1`
		if [ -n "$result" ];
		then
			STORAGEAT="/dev/sdb"
			DISKAT1="/dev/sdb1"
			result=`fdisk -l | grep Linux | grep /dev/sdb2`
			if [ -n "$result" ];
			then
				DISKAT2="/dev/sdb2"
				DISKAT3="/dev/sdb3"
				DISKAT4="/dev/sdb4"
			fi
		fi
	fi
}
# --------------------------------------------main code here--------------------------------------
# it's important to _mount_ the internal usb to $USBDRIVE1 even if it's not being used
# otherwise it will interfere with backup / sync / restore usb functionality
/usr/local/bin/sendchild "Starting Clock" "" ""

# stop programs
/etc/init.d/clock stop



# unmount any drives attached to /mnt/1 or $USBDRIVE1
result=` mount | grep /mnt/1`
if [ -n "$result" ];
then
	umount /mnt/1
fi

result=` mount | grep $USBDRIVE1`
if [ -n "$result" ];
then
	umount $USBDRIVE1
fi

result=` mount | grep $USBDRIVE2`
if [ -n "$result" ];
then
	umount $USBDRIVE2
fi


result=` mount | grep $USBDRIVE3`
if [ -n "$result" ];
then
	umount $USBDRIVE3
fi

result=` mount | grep $USBDRIVE4`
if [ -n "$result" ];
then
	umount $USBDRIVE4
fi

#   detect existing stuff
linux_find
if [ -n "$STORAGEAT" ];
then
	information  "Linux partition found"
	if [ -n "$DISKAT2" ];
	then
		check_disk $DISKAT1
	fi	
	if [ "$?" -eq "0" ]; 
	then
	  mount_data
		if [ "$?" -ne "0" ]; 
		then
			echo Unable to Mount USB drive.
			# possibly fall back on $MNTFLASH here?
			exit
		fi
	else
	  /usr/local/bin/sendchild "Starting Clock" "Reboot Required" "Rebooting" ""
		reboot
		exit
	fi	
  if [ -n "$DISKAT2" ];
	then
		READY="Yes"
	else
		# only has 1 linux partition. So move data off drive, and reformat, and move back
		change_format
		if [ "$?" -eq "2" ]; 
		then
			# unable to move back to mnt flash. So leave as is for now
			READY="Yes"
		else
			READY="Yes"
		fi
	fi
else
	# no linux disk. probably win95 disk, or no disk at all.
	information  "Linux partition not found"
	find_win95 vfat -o umask=0000  
	if [ "$?" -eq "0" ]; 
	then
		information "FAT partition found, attempting reformat"
	  change_format # strong attempt to format usb drive to ext4 unless data on usb is too large.
		if [ "$?" -eq "2" ]; 
		then
			# unable to move back to mnt flash. So leave as is for now
			READY="Yes"
		else
			READY="Yes"
		fi
	else
	  # no usb stick (with CSTimeClockFixedStorage_DNR) found
		information "FAT partition not found"
		make_sure using_mnt_flash	
		READY="Yes"
  fi	
fi	

#----- some start-up maintainence
chmod 0777 /var/tmp
chmod 0777 /etc
chmod 0777 /etc/init.d
chmod 0777 /usr/local/bin
chmod 0777 /usr/local/lib

if [ -n "$READY" ];
then
	switch_drive
	/usr/local/bin/sendchild "Starting Clock" "Checking Database" "Format" ""
	information "Running alter.sql to make sure database is the right version"
  /usr/local/bin/sqlite3shell /var/local/data/capeclock.db < /usr/local/bin/alter.sql > /var/null
	/etc/init.d/clock start
fi	


#  -n str1 True if str1 is not null (length is greater than zero).
#  -z str1 True if str1 is null (length is zero).


# to switch from internal flash to usb flash change file
# /usr/local/bin/using_mnt_flash to 
# /usr/local/bin/switch_to_usb_flash eg
# mv /usr/local/bin/using_mnt_flash /usr/local/bin/switch_to_usb_flash
# then re boot

# to switch from usb flash to mount flash change file
# /usr/local/bin/using_usb_flash to 
# /usr/local/bin/switch_to_mnt_flash eg
# mv /usr/local/bin/using_usb_flash /usr/local/bin/switch_to_mnt_flash
# then re boot

# to see what it is currently set to do a
# ls -l /var/local
# if result shows $USBFLASH then using usb
# if result shows $MNTFLASH then using mnt

#Superblock backups stored on blocks:
#        32768, 98304, 163840, 229376, 294912


