#!/bin/bash
# package:		Part of VPL-Jail-System
# copyright:    Copyright (C) 2014 Juan Carlos Rodriguez-del-Pino
# license:      GNU/GPL, see LICENSE.txt or http://www.gnu.org/licenses/gpl.txt
# Description:  Script to install VPL-Jail-System

echo "Running with parameters: $@"

# Fixes UID if needed
if [ -z "$UID" ] ; then
	UID=$(id -u)
	EUID=$(id -u -r)
fi
# Checks running as root
if [ "$UID" != "0" ] && [ "$EUID" != "0" ] ; then
	echo "This script must be run as the root user."
	echo "Currently, it is being run as user $USER with UID $UID and EUID $EUID."
	exit 1
fi

umask 077

LOGFILE=/var/log/vpl_installation.log
VPL_PROGRAMS_DIR=/usr/sbin/vpl
VPL_CONFIG_DIR=/etc/vpl

{
	touch "$LOGFILE"
	chmod 600 "$LOGFILE"
	date > "$LOGFILE"
	exec &> >(tee "$LOGFILE")
} &> /dev/null

function vpl_detect_package_manager() {
	# Detect package manager (DNF/APT/APK)
	if [ "$(command -v dnf)" != "" ] ; then
		echo "Using DNF package manager" 
		echo "Upgrading installed software"
		dnf -y -q check-update >> "$LOGFILE"
		dnf -y -q upgrade >> "$LOGFILE"
		function vpl_install_base {
			dnf -y -q install $1 >> "$LOGFILE"
			return $?
		}
		function vpl_uninstall_base {
			dnf -y -q remove $1 >> "$LOGFILE"
			return $?
		}
		function vpl_install_check {
			dnf -y -q list $1 &> /dev/null
			return $?
		}
		PMTYPE="dnf"
	elif [ "$(command -v yum)" != "" ] ; then
		echo "Using YUM deprecated package manager" 
		echo "Upgrading installed software"
		yum -y -q check-update >> "$LOGFILE"
		yum -y -q upgrade >> "$LOGFILE"
		function vpl_install_base {
			yum -y -q install $1 >> "$LOGFILE"
			return $?
		}
		function vpl_uninstall_base {
			yum -y -q remove $1 >> "$LOGFILE"
			return $?
		}
		function vpl_install_check {
			yum -y -q list $1 &> /dev/null
			return $?
		}
		PMTYPE="dnf"
	elif [ "$(command -v apt-get)" != "" ] ; then
		echo "Using APT package manager"
		echo "Upgrading installed software"
		apt-get -q update >> "$LOGFILE"
		apt-get -q -y upgrade >> "$LOGFILE"
		function vpl_install_base {
			apt-get -q -y --allow-unauthenticated install $1 >> "$LOGFILE"
			return $?
		}
		function vpl_uninstall_base {
			apt-get -q -y remove $1 >> "$LOGFILE"
			return $?
		}
		function vpl_install_check {
			apt-cache pkgnames $1 | grep -q -x -F $1 &> /dev/null
			return $?
		}
		PMTYPE="apt"
		if [ "$(command -v add-apt-repository)" != "" ] ; then
			add-apt-repository -y universe &> /dev/null
		fi

	elif [ "$(command -v apk)" != "" ] ; then
		echo "Using APK package manager"
		echo "Updagrading installed software"
		apk --no-interactive update >> "$LOGFILE"
		apk --no-interactive upgrade >> "$LOGFILE"
		function vpl_install_base {
			apk --no-interactive add $1 >> "$LOGFILE"
			return $?
		}
		function vpl_uninstall_base {
			apk --no-interactive del $1 >> "$LOGFILE"
			return $?
		}
		function vpl_install_check {
			apk --no-interactive add $1 &> /dev/null
			return $?
		}
		PMTYPE="apk"
	else
	    echo "Unable to detect the package manager."
		echo "Please ensure your system uses one of the supported package managers: APT, DNF, or APK."
		exit 1
	fi
}

function vpl_detect_service_manager(){
	# Detect service manager
	if [ "$(command -v systemctl)" != "" ] ; then
		echo "Using systemd service manager"	 
		function vpl_install_service {
			cp vpl-jail-system.initd $VPL_PROGRAMS_DIR/vpl-jail-system
			chmod +x $VPL_PROGRAMS_DIR/vpl-jail-system
			cp vpl-jail-system.service /etc/systemd/system/vpl-jail-system.service
			systemctl daemon-reload
			systemctl enable vpl-jail-system
		}
		function vpl_stop_service {
			systemctl stop vpl-jail-system
		}
		function vpl_start_service {
			systemctl start vpl-jail-system
		}
		function vpl_info_using_service {
			echo
			echo "------------------------------------------------------"
			echo "Note: Use the following command to manage the service."
			echo "systemctl [start|stop|status] vpl-jail-system"
		}
		SMANAGER="1"
	elif [ -x /sbin/init ] ; then
		echo "Using system V service manager"	 
		function vpl_install_service {
			cp vpl-jail-system.initd $VPL_PROGRAMS_DIR/vpl-jail-system
			chmod +x $VPL_PROGRAMS_DIR/vpl-jail-system
			cp vpl-jail-system.initd /etc/init.d/vpl-jail-system
			chmod +x /etc/init.d/vpl-jail-system
			if [ "$(command -v update-rc.d)" != "" ] ; then
				update-rc.d -f vpl-jail-system remove >> "$LOGFILE"
				update-rc.d vpl-jail-system defaults >> "$LOGFILE"
			else
				if [ "$(command -v chkconfig)" != "" ] ; then
					chkconfig --add vpl-jail-system  >> "$LOGFILE"
				else
					echo "WARNING: The service was not installed because neither"
					echo "update-rc.d nor chkconfig was found."
				fi
			fi
		}
		function vpl_stop_service {
			service vpl-jail-system stop
		}
		function vpl_start_service {
			service vpl-jail-system start
		}
		function vpl_info_using_service {
			echo
			echo "-------------------------------------------------------"
			echo "Notice: you may use next command to control the service"
			echo "service vpl-jail-system [start|stop|status|start_foreground]"
		}
		SMANAGER="2"
	else
		echo "Unknown service manager"	 
		function vpl_install_service {
			cp vpl-jail-system.initd $VPL_PROGRAMS_DIR/vpl-jail-system
			chmod +x $VPL_PROGRAMS_DIR/vpl-jail-system
			echo "You must install the service manually."
			echo "The script to start, stop, etc. the service is:"
			echo "/usr/sbin/vpl/vpl-jail-system"
		}
		function vpl_stop_service {
			echo "You must run:"
			echo "/usr/sbin/vpl/vpl-jail-system stop"
		}
		function vpl_start_service {
			echo "You must run:"
			echo "/usr/sbin/vpl/vpl-jail-system start"
		}
		function vpl_info_using_service {
			echo
			echo "-------------------------------------------------------"
			echo "Notice: you may use next command to control the service"
			echo "/usr/sbin/vpl/vpl-jail-system [start|stop|restart|start_foreground]"
		}
		SMANAGER="3"
	fi
}

function vpl_check_selinux {
	if [ "$(command -v setenforce)" != "" ] ; then
		echo "----------------------------------------------------"
		echo "Your system seems to be using SELinux."
		echo "You may need to disable or configure SELinux to install and run vpl-jail-system service"
		echo "To reactivate the vpl-jail-system service run:"
		echo "  systemctl daemon-reload"
		echo "  systemctl enable vpl-jail-system"
		echo "  systemctl start vpl-jail-system"
	fi
}

function vpl_install_package {
	if [ "$LISTPACKAGES" != "" ] ; then
		echo -n "  $1 -> "
		shift
		while [ "$#" != "0" ] ; do
			echo -n $1
			shift
			if [ "$#" != "0" ] ; then
				echo -n " or "
			fi
		done
		echo ""
		return
	fi
	local found=0
	local checked=""
	echo -n "Installing $1: "
	shift
	while [ "$#" != "0" ] ; do
		checked="$checked $1"
   		vpl_install_check $1
		if [ $? -eq 0 ] ; then
	   	   echo -n $1
	       vpl_install_base $1
	   	   if [ $? -eq 0 ] ; then
	   	   		found=1
	   	   		echo " [OK]"
	   	   else
	   	   		echo " [ERROR]"
	   	   fi
	       break
   	   fi
       shift
   done
   if [ $found -eq 0 ] ; then
   	   echo "[Package not found. Checked:$checked]"
   fi
}

function vpl_install_npm_check {
    vpl_install_check npm
	if [ $? -eq 0 ] ; then
		vpl_install_base npm
	fi
}

function vpl_install_npm {
	if [ "$LISTPACKAGES" != "" ] ; then
		echo -n "  $1 -> npm "
		shift
		while [ "$#" != "0" ] ; do
			echo -n $1
			shift
			if [ "$#" != "0" ] ; then
				echo -n " or "
			fi
		done
		echo ""
		return
	fi
    vpl_install_check npm
	if [ $? -eq 0 ] ; then
		vpl_install_base npm
	fi
	local found=1
	local checked=""
	echo -n "Installing $1 (using npm): "
	shift
	while [ "$#" != "0" ] ; do
	    checked="$checked $1"
   	    npm install -g $1 &> /dev/null
   	    if [ $? -eq 0 ] ; then
   	   	    echo " [OK]"
	        found=0
   	   	    break
   	    fi
        shift
   done
   if [ $found -eq 1 ] ; then
   	   echo "[Package npm not found. Checked$checked"
   fi
}


function vpl_installq {
   echo -n "Do you want to install $1 (y/n) "
   A="y"
   read A
   if [ "$A" == "y" ] ; then
        vpl_install_package $@
   fi
}

function vpl_install_letsencrypt {
	vpl_install_package "Let's Encrypt" certbot
	if [ "$(command -v certbot)" = "" ] ; then
		echo "Error: certbot not installed."
		echo "Please install certbot manually"
		exit 0
	fi
	local DETECTEDFQDN=""
	local HNAME=""
	if [ "$(command -pv dnsdomainname)" != "" ] ; then
		DETECTEDFQDN=$(dnsdomainname -A)
		# Trim FQDN name
		DETECTEDFQDN=$(echo $DETECTEDFQDN)
	fi
	echo "Please, enter the domain name (FQDN) of this machine in order to install the configure Certbot."
	echo -n "($DETECTEDFQDN): "
	read HNAME
	if [ "$HNAME" == "" ] ; then
		HNAME=$DETECTEDFQDN
	fi
	certbot certonly --standalone --preferred-challenges http -d $HNAME
	systemctl enable --now certbot.timer
	echo "pre_hook = systemctl stop vpl-jail-system" >> /etc/letsencrypt/renewal/$HNAME.conf
	echo "post_hook = systemctl start vpl-jail-system" >> /etc/letsencrypt/renewal/$HNAME.conf
	ln -s /etc/letsencrypt/live/$HNAME/fullchain.pem /etc/vpl/cert.pem 2> /dev/null 
	ln -s /etc/letsencrypt/live/$HNAME/privkey.pem /etc/vpl/key.pem 2> /dev/null
	echo "Note: commonly the renewal of the certificate is checked twince a day,"
	echo "      this action require stop and start the vpl-jail-service."
}

function vpl_install_jgrasp {
	local URLBASE="https://www.jgrasp.org/dl4g/jgrasp/"
	local VERSION="205_04"
	local FILENAME="jgrasp205_04.zip"
	local CDIR=""
	vpl_install_package "wget" wget &> /dev/null
	while true ; do
		echo -n "Version number of JGrasp to install e.g. 2.0.5_04 (0 to exit)"
		read VERSION
		if [ "$VERSION" == "0" ] ; then
			break
		fi 
		VERSION=$(echo $VERSION | sed 's/\.//g')
		FILENAME="jgrasp$VERSION.zip"
		wget -q $URLBASE$FILENAME
		if [ "$?" == "0" -a -f "$FILENAME" ] ; then
			unzip $FILENAME > /dev/null
			if [ -d "jgrasp" ] ; then
				rm -R /usr/local/jgrasp 2> /dev/null
				rm /usr/bin/jgrasp 2> /dev/null
				mv jgrasp /usr/local/jgrasp
				ln -s /usr/local/jgrasp/bin/jgrasp /usr/bin/jgrasp
				CDIR=$(pwd)
				cd /usr/local/jgrasp/src
				./configure > /dev/null
				./Make.sh
				if [ "$?" == "0" ] ; then
					cd $CDIR
					break
				else
					cd $CDIR
					echo "Error compiling code. Try again"
				fi
			else
				echo "Error uncompressing package, jgrasp dir not found. Try again"
			fi
		else
			echo "Version not found. Try gain."
		fi
	done
}

function vpl_install_kotlin {
	local URLBASE="https://github.com/JetBrains/kotlin/releases/download/"
	local VERSION="1.4.21"
	local FILENAME=""
	local CDIR=""
	vpl_install_package "wget" wget &> /dev/null
	while true ; do
		echo -n "Version number of Kotlin to install e.g. 1.4.21 (0 to exit)"
		read VERSION
		if [ "$VERSION" == "0" ] ; then
			break
		fi
		SUBDIR="v$VERSION/"
		FILENAME="kotlin-compiler-$VERSION.zip"
		wget -q $URLBASE$SUBDIR$FILENAME
		if [ "$?" == "0" -a -f "$FILENAME" ] ; then
			unzip $FILENAME > /dev/null
			if [ -d "kotlinc" ] ; then
				DESTINATION=/opt/kotlin
				rm -R $DESTINATION 2> /dev/null
				mv kotlinc $DESTINATION
				ln -s $DESTINATION/bin/kotlinc /usr/bin/kotlinc
				break
			else
				echo ""
				echo "Error uncompressing package, jgrasp dir not found. Try again"
				echo ""
			fi
		else
			echo "Version not found. Try gain."
		fi
	done
}

function vpl_generate_selfsigned_certificate {
	local A=""
	local HNAMEW=$(hostname --long| sed 's/^[^\.]*/\*/g')
	local HNAME=$(hostname --long)
	local INAME
	echo "Generating self-signed SSL certificate for $HNAME machine"
	#Get host name to generate the certificate
	echo -n "Do you want a certificate with wildcard for a set of servers ($HNAMEW)? (y/n)"
	read A
	if [ "$A" == "y" ] ; then
		INAME=$HNAMEW
	else
		INAME=$HNAME
	fi
	if [ "$INAME" = "" ] ; then
		INAME=localhost
	fi
	#Generate key
	openssl genrsa -passout pass:12345678 -des3 -out key.pem 2048
	#Generate certificate for this server
	echo -n "Do you want to customize the certificate info? (y/n)"
	read A
	if [ "$A" == "y" ] ; then
		openssl req -new -key key.pem -out certini.pem -passin pass:12345678
	else
		local SUBJ="/C=ES/ST=State/L=Location/O=VPL/OU=Execution server/CN=$INAME"
		openssl req -new -subj "$SUBJ" -key key.pem -out certini.pem -passin pass:12345678
	fi
	#Remove key password
	cp key.pem keyini.pem
	openssl rsa -in keyini.pem -out key.pem -passin pass:12345678
	#Generate self signed certificate for 5 years
	openssl x509 -in certini.pem -out cert.pem -req -signkey key.pem -days 1826 
}

function vpl_show_help() {
	echo ""
    echo "---------------------------------------------------"
    echo "VPL-Jail-System Installer"
    echo ""
    echo "This script is used to install the VPL-Jail-System."
    echo "Note: you can install manually all the development software you want to use."
    echo "Usage: ./install-vpl.sh [OPTIONS]"
    echo ""
    echo "OPTIONS:"
    echo "  help           Show this help message and exit."
    echo "  update         Update the VPL-Jail-System server software."
    echo "  start          Start the VPL-Jail-System service after installation."
    echo "  noninteractive Install without user interaction."
    echo "  uninstall      Uninstall all development packages leaving the minimum required."
    echo "  [inst_level]   Install programming languages development packages:"
	echo "                 values [minimum | basic | standard | full]"
	echo "  list           Show the packages to install by [inst_level]"
    echo ""
    echo "EXAMPLES:"
    echo "  ./install-vpl.sh update"
	echo "         Update the VPL-Jail-System server software."
    echo "  ./install-vpl.sh standard noninteractive start"
	echo "         Install in non-interactive mode standard packages and start server."
    echo "  ./install-vpl.sh full"
	echo "         Install all known dev packages in interactive mode."
}

function vpl_install_update_daemon() {
	echo "Preparing daemon compilation"
	[ -x "$(command -v autoreconf)" ] && (autoreconf --force -i &> /dev/null)
	./configure -q
	[ $? -ne 0 ] && ./configure -q --disable-dependency-tracking
	echo "Compiling daemon (vpl-jail-server)"
	make >> "$LOGFILE"
	if [ -d $VPL_CONFIG_DIR ] ; then
		echo "Updating installation => $VPL_CONFIG_DIR"
		if [ -n "$(ps -e | grep -q vpl-jail-server)" ] ; then
			echo "Stop service"
			vpl_stop_service >> "$LOGFILE"
			local NEED_RESTART=yes
		fi
	else
		echo "Installing => $VPL_CONFIG_DIR"
		mkdir -p $VPL_CONFIG_DIR
	fi
	mkdir -p $VPL_PROGRAMS_DIR
	#Copy daemon
	if [ ! -x "src/vpl-jail-server" ] ; then
		echo "Error compiling vpl-jail-server. See logs for more details"
		exit 1
	fi
	cp src/vpl-jail-server $VPL_PROGRAMS_DIR
	if [ "$?" != "0" ] ; then
	 	echo "Error: The daemon update failed (old daemon still running?)"
		echo "        Please, stop the service or daemon manually and retry update."
		exit 1
	fi
	echo "New daemon (vpl-jail-server) installed"
	[ -n "$NEED_RESTART" ] && (echo "Start service" ; vpl_start_service >> "$LOGFILE")
}

function vpl_install_update_extra_files() {
	local VPL_CONFIGFILE=$VPL_CONFIG_DIR/vpl-jail-system.conf
	if [ -f $VPL_CONFIGFILE ] ; then
		local A=""
		if [ "$NONINTERACTIVE" == "" ] ; then
			echo "Replace current configuration file with a fresh one?"
			echo -n "(y/n)"
			read A
		fi
		if [ "$A" == "y" ] ; then
			cp vpl-jail-system.conf $VPL_CONFIGFILE
			echo "Configuration file replaced"
		else
			echo "Configuration file keeped"
		fi
	else
		cp vpl-jail-system.conf $VPL_CONFIGFILE
		echo "Default configuration file installed"
		if [ "$PMTYPE" = "dnf"  ] ; then
			echo "" >> $VPL_CONFIGFILE
			echo "ENVPATH=/usr/bin:/bin" >> $VPL_CONFIGFILE
			echo "Configuration file changed. Added ENVPATH"
		fi
	fi
	chmod 600 $VPL_CONFIGFILE

	# Copy launch scripts
	echo "Installing launch scripts"
	cp launchers/*.sh $VPL_PROGRAMS_DIR
	chmod +x $VPL_PROGRAMS_DIR/*.sh

	# Update vpl-jail-system
	cp vpl-jail-system.initd $VPL_PROGRAMS_DIR/vpl-jail-system

	# Create default control dir
	mkdir -p /var/vpl-jail-system
	chmod 0600 /var/vpl-jail-system
}

function vpl_process_packages_file() {
	[ ! -s "$1" ] && (echo "Package file '$1' not found" ; return)
	local npm_command=$3
	local package_command=$4
	echo "$2 from $1"
	local line
	local name
	local packages
	while read -r line
	do
		echo "$line" | grep -q "^ *#"
		[ $? = 0 ] && continue
		echo "$line" | grep -q "^ *npm "
		if [ $? = 0 ] ; then
			name=$(echo $line | sed -e "s/^ *npm \+\"\([^\"]\+\)\".*/\1/")
			packages=$(echo $line | sed -e "s/.*\"[^\"]\+\"\(.*\)/\1/")
			[ -n "$packages" ] && $npm_command "$name" $packages
		else
			name=$(echo $line | sed -e "s/.*\"\([^\"]\+\)\".*/\1/")
			packages=$(echo $line | sed -e "s/.*\"[^\"]\+\"\(.*\)/\1/")
			[ -n "$packages" ] && $package_command "$name" $packages
		fi
	done < "$1"
}

function vpl_install_packages_file() {
	vpl_process_packages_file "$1" "Installing" vpl_install_npm vpl_install_package
}

function vpl_install_minimum() {
	echo ""
	echo "Minimum required packages"
	local PACKAGE_LIST_FILE="packages_files/minimum.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_install_packages_file $PACKAGE_LIST_FILE
	if [ "$(command -v gconftool-2)" != "" ] ; then
		gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t string --set /apps/metacity/general/theme Redmond
	fi
	echo
}

function vpl_install_basic() {
	echo ""
	echo "Basic aditional packages"
	local PACKAGE_LIST_FILE="packages_files/basic.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_install_packages_file $PACKAGE_LIST_FILE
	if [ "$PMTYPE" = "apt" ] ; then
		if [ "$(command -v update-alternatives)" != "" -a "$LISTPACKAGES" == "" ] ; then
			update-alternatives --auto java
			update-alternatives --auto javac
		fi
	fi
	echo
}

function vpl_install_standard() {
	echo ""
	echo "Standard aditional packages"
	local PACKAGE_LIST_FILE="packages_files/standard.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_install_packages_file $PACKAGE_LIST_FILE
	echo
}

function vpl_install_full() {
	echo ""
	echo "Full aditional packages"
	local PACKAGE_LIST_FILE="packages_files/full.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_install_packages_file $PACKAGE_LIST_FILE
	if [ "$LISTPACKAGES" != "" ] ; then
		echo "  JGrasp (requires user intervention) "
		echo "  Kotlin (requires user intervention) "
		echo
		return
	fi

	if [ "$NONINTERACTIVE" == "" ] ; then
		echo "Do you want to try to install Kotlin?"
		echo -n "(y/n)"
		read A3
		if [ "$A3" != "n" ] ; then
			vpl_install_kotlin
		fi
		echo "Do you want to try to install JGrasp?"
		echo -n "(y/n)"
		read A4
		if [ "$A4" != "n" ] ; then
			vpl_install_jgrasp
		fi
	fi
}

function vpl_uninstall_package {
	local checked=""
	echo -n "Uninstalling $1: "
	shift
	while [ "$#" != "0" ] ; do
		checked="$checked $1"
	    vpl_uninstall_base $1
   	    if [ $? -eq 0 ] ; then
   	   		echo " [OK]"
   	    else
   	   		echo " [FAILED/NOT FOUND]"
   	    fi
        shift
   done
}

function vpl_uninstall_npm {
    if [ "$(command -v npm)" == "" ] ; then
       return
    fi
	echo -n "Uninstalling $1 (using npm): "
	shift
	while [ "$#" != "0" ] ; do
   	    npm uninstall -g $1 &> /dev/null
   	    if [ $? -eq 0 ] ; then
   	   	    echo " [OK]"
   	    fi
        shift
   done
}

function vpl_uninstall_packages_file() {
	vpl_process_packages_file "$1" "Uninstalling" vpl_uninstall_npm vpl_uninstall_package
}

function vpl_uninstall_full_leaving_minimum() {
	if [ "$NONINTERACTIVE" == "" ] ; then
		echo ""
		echo "WARNING:"
		echo "This action will uninstall all development packages in the full set"
		echo "except for those in the minimum set."
		echo "This script cannot determine if a package was installed by this script or manually."
		echo "Therefore, packages installed manually or by other means may be removed."
		echo "Custom configurations or packages depending on the removed packages might be affected."
		echo -n "Are you sure you want to proceed? (y/n) "
		read A
		if [ "$A" != "y" ] ; then
			echo "Uninstall aborted."
			return
		fi
	fi
	echo ""
	echo "Uninstalling Full, Standard and Basic packages"
	local PACKAGE_LIST_FILE="packages_files/full.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_uninstall_packages_file $PACKAGE_LIST_FILE
	PACKAGE_LIST_FILE="packages_files/standard.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_uninstall_packages_file $PACKAGE_LIST_FILE
	PACKAGE_LIST_FILE="packages_files/basic.$PMTYPE.lst"
	[ -s $PACKAGE_LIST_FILE ] && vpl_uninstall_packages_file $PACKAGE_LIST_FILE

	if [ -d "/opt/kotlin" ]; then
        echo "Removing Kotlin"
        rm -R /opt/kotlin
        rm /usr/bin/kotlinc
    fi
    
    if [ -d "/usr/local/jgrasp" ]; then
         echo "Removing JGrasp"
         rm -R /usr/local/jgrasp
         rm /usr/bin/jgrasp
    fi
    echo "Done."
}

function vpl_check_SSL_certificate() {
	if [ ! -f $VPL_CONFIG_DIR/key.pem ] ; then
		if [ "$NONINTERACTIVE" == "" ] ; then
			echo "VPL execution server needs SSL certificates to accept https:"
			echo "and wss: requests."
			echo "If you have certificates then copy the key and the certificate file"
			echo "in pem format to $VPL_CONFIG_DIR/key.pem and $VPL_CONFIG_DIR/cert.pem ."
			echo "If you do not have a certificate, the installer can automatically install"
			echo "and configure the Let's Encrypt certbot in standalone mode for you."
			echo "If you want to use certbot in webroot mode you must install and configure it manually (answer n)."
			echo "Notice that this machine must be accesible from internet and has port 80 available."
			echo -n "Install Let's Encrypt in standalone mode to get and renew free certificates?"
			echo -n "(y/n)"
			read A	
			if [ "$A" != "n" ] ; then
				vpl_install_letsencrypt	
			else
				echo "If you want the intaller can generate a selfsigned certificate for you."
				echo -n "Generate the certificate?"
				read A
				if [ "$A" != "n" ] ; then
					vpl_generate_selfsigned_certificate
					cp key.pem $VPL_CONFIG_DIR
					cp cert.pem $VPL_CONFIG_DIR
					chmod 600 $VPL_CONFIG_DIR/*.pem
					rm key.pem keyini.pem certini.pem cert.pem
				fi
			fi
		fi
	fi
}

function vpl_commandline_config_arg() {
	case "$1" in
		start)
			export START=yes
			;;
 		noninteractive)
			export NONINTERACTIVE=yes
			export DEBIAN_FRONTEND=noninteractive
			;;
		minimum)		
			export MINIMUM=yes
			;;
		basic)
			export MINIMUM=yes
			export BASIC=yes
			;;
		standard)
			export MINIMUM=yes
			export BASIC=yes
			export STANDARD=yes
			;;
		full)
			export MINIMUM=yes
			export BASIC=yes
			export STANDARD=yes
			export FULL=yes
			;;
		*)
			[ -z "$ACTION_ARG" ] && ACTION_ARG=$1
			;;
	esac
}

function vpl_commandline_action_arg() {
	case "$1" in
		help)
			vpl_show_help
			;;
		update)
			vpl_install_update_daemon
			vpl_install_update_extra_files
			[ -z "$NONINTERACTIVE" ] && vpl_info_using_service
			;;
		uninstall)
			vpl_uninstall_full_leaving_minimum
			;;
		list)
			export LISTPACKAGES=yes
			vpl_install_minimum
			[ "$BASIC" != "" ] && vpl_install_basic
			[ "$STANDARD" != "" ] && vpl_install_standard
			[ "$FULL" != "" ] && vpl_install_full
			;;
		*)
			echo ""
			echo " => Error: unknow parameter '$1'"
			vpl_show_help
			exit 1
			;;
	esac
	exit 0
}

vpl_detect_package_manager
vpl_detect_service_manager

echo "Installation log file => $LOGFILE"
while [ $# -gt 0 ] ; do
	vpl_commandline_config_arg "$1"
	shift
done

[ -n "$ACTION_ARG" ] && vpl_commandline_action_arg $ACTION_ARG

if [ "$MINIMUM" == "" ] ; then
	vpl_show_help
	exit 1
fi
vpl_install_minimum
vpl_install_update_daemon
vpl_install_update_extra_files
vpl_install_service
vpl_check_SSL_certificate

[ "$BASIC" != "" ] && vpl_install_basic
[ "$STANDARD" != "" ] && vpl_install_standard
[ "$FULL" != "" ] && vpl_install_full

echo "-----------------------------------------------------------------"
echo "If you are planning to use apache2, nginx or other service,"
echo "notice that you must use different ports that in vpl-jail-system."

if [ "$START" == "yes" ] ; then
	vpl_check_selinux
	echo "Starting the service (vpl-jail-system)"
	vpl_start_service
fi
vpl_info_using_service
