#!/bin/bash
# package:		Part of vpl-xmlrpc-jail
# copyright:	Copyright (C) 2011 Juan Carlos Rodríguez-del-Pino. All rights reserved.
# license:		GNU/GPL, see LICENSE.txt or http://www.gnu.org/licenses/gpl-3.0.html
# Description:	Script to uninstall vpl-xmlrpc-jail (Centos 5.5 and Ubuntu)

read_config_var(){
	local FILE=$1
	shift
	while (( "$#" )); do
		local RES=$(grep -i -e "^[ \\t]*$1[ \\t]*=" $FILE \
	             | tail -n 1 \
	             | sed -e "s/^[ \\t]*$1[ \\t]*=[ \\t]*\\(.*\\)\$/\\1/I")
	    if [ "$RES" == "" ] ; then
	    	echo "Param read from config $1=$2" >> $LOGFILE
	    	export $1=$2
	    else
	    	echo "Param using default $1=$RES" >> $LOGFILE
	    	export $1=$RES
	    fi
		shift
		shift
	done
}

remove_dir() {
	if [ "$1" != "/" ] && [ -d $1 ] ; then
		echo "Please, remove dir $1"
	fi
}
if [ "$UID" != "0" ] && [ "$EUID" != "0" ] ; then
    echo "This script need to be run as root and is run as $USER uid $UID euid $EUID"
    exit 1;
fi
VPLJAIL_INSTALL_DIR=/etc/vpl
if [ ! -d $VPLJAIL_INSTALL_DIR ] ; then
	echo "VPL jail installation dir '$VPLJAIL_INSTALL_DIR' not found"
	exit 1
fi
LSYSTEM="Unknow"
if [ -f /sbin/chkconfig ] ; then
	LSYSTEM="1"
fi
if [ -f /usr/sbin/update-rc.d ] ; then
	LSYSTEM="2"
fi

#Stop services
service vpl-jail-system stop
CONFIG_FILE="$VPLJAIL_INSTALL_DIR/vpl-jail-system.conf"
JAILPATH=/jail
CONTROLPATH=/var/vpl-jail-system
#Load config file
if [ -f "$CONFIG_FILE" ] ; then
	read_config_var "$CONFIG_FILE" JAILPATH /jail
	read_config_var "$CONFIG_FILE" CONTROLPATH /var/vpl-jail-system
	#Check $JAILPATH not been "/"
	if [ -f "$JAILPATH$CONFIG_FILE" ] ; then
		echo "vpl-jail-system jail path error '$JAILPATH'"
		exit 1
	else
		#Remove safe dir
		remove_dir $JAILPATH
		remove_dir $CONTROLPATH
	fi
else
	echo "vpl-jail-system config file not found: $CONFIG_FILE"
fi
if [ "$LSYSTEM" = "1" ] ; then
	chkconfig --del vpl-jail-system
else
	update-rc.d -f vpl-jail-system remove
fi

if [ -f /bin/systemctl ] ; then
	systemctl stop vpl-jail-system
	systemctl disable vpl-jail-system
	rm /etc/systemd/system/vpl-jail-system*
	systemctl daemon-reload
	systemctl reset-failed
fi
rm /etc/init.d/vpl-jail-system* &> /dev/null
rm -Rf $VPLJAIL_INSTALL_DIR

