#!/bin/sh

Script_Ver="1.00"

InitMember(){
	softwarename="Perspective Workstation"
	
	host="127.0.0.1:8088"
	downloadpath="/system/nativelaunch?os=linux&type=workstation"
	
	installpath="/usr/local/bin"
	appname="perspectiveworkstation"
	apppath="${installpath}/${appname}"
	
	archivefile="perspectiveworkstation.tar.gz"
	shortcutfile="/usr/share/applications/${appname}.desktop"
	iconfile="${apppath}/app/launcher.png"
}

ShowTitle() {
    echo ""
    echo "(*) Software installer for ${softwarename} "
	echo "(*) Script Version = ${Script_Ver} "
    echo ""
}

CheckPermission() {
    echo -n "(I) Check user permission:"
    account=`whoami`
    if [ ${account} = "root" ]; then
        echo " ${account}, you are the supervisor."
    else
        echo " ${account}, you are NOT the supervisor."
        echo "(E) The root permission is required to run this installer."
        echo ""
        exit 1
    fi
}

DownloadSoftware(){
	if [ -e ${archivefile} ]; then
		Cleanup
	fi

	apt-get update
	apt-get install -y wget curl
	
	wget -O ${archivefile} --no-check-certificate http://${host}${downloadpath}
	tar -xf ${archivefile} -C ${installpath}
}

Cleanup(){
	if [ -e ${archivefile} ]; then
		echo "(I) Removing dowloaded archive file."
		rm ${archivefile}
	fi
}

InstallSoftware(){
	if [ -e ${apppath} ]; then
		echo "(W) The software folder already exists!"
		RemoveSoftware
	fi

	echo "(I) Extracting software to ${apppath}."
	tar -xf "${archivefile}" -C "${installpath}"
	
	echo "(I) Setting permissions."
	chown -R admin:admin ${apppath}
	chmod 755 ${apppath}
}

RemoveSoftware(){
	if [ -e ${apppath} ]; then	
		echo "(I) Removing existing software folder at ${apppath}."
		echo ""
		
		rm -rf ${apppath}
	fi
}

AddShortcut() {
	/bin/cat <<EOM >$shortcutfile
[Desktop Entry]
Type=Application
Terminal=false
Icon=${iconfile}
Name=${softwarename}
Comment=Launch the ${softwarename}
Categories=Office;Ignition;
Exec=bash -c 'cd "${apppath}/app" && ./${appname}.sh &' . %k
EOM

}

RemoveShortcut() {
	if [ -e ${shortcutfile} ]; then	
		echo "(I) Removing shortcut icon from application list."
		rm ${shortcutfile}
	fi
}

if [ $# = 0 ]; then
	SilentMode="false"
	clear
	ShowTitle
	CheckPermission
	InitMember
	
	DownloadSoftware
	InstallSoftware
	AddShortcut
	Cleanup
	
	echo ""
   	echo "(I) ${softwarename} has been installed successfully."
	#echo "(I) Please reboot the system."
elif [ $# -ge 1 ]; then
	if [ $1 = "uninstall" ]; then
		SilentMode="false"
		clear
		ShowTitle
		CheckPermission
		InitMember
		
		RemoveShortcut
		RemoveSoftware
		
       	echo ""
       	echo "(I) ${softarename} has been removed successfully."
       	#echo "(I) Please reboot the system."
	fi
fi

