#! /bin/sh
#
# ++Copyright Product++
#
# Copyright (c) 2009-2011 Packet General Networks, Inc. ("PGN").
# All rights reserved.
#
# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF PGN
# The copyright notice above does not evidence any actual
# or intended publication of such source code.
#
# Please refer to the file COPYRIGHT and the PGN Source Code Product
# License Agreement for the specific terms and conditions.
#
# Packet General Networks, Inc.
# 865 Merrick Road, Suite 204
# Baldwin, New York 11510
#
# +1.631.546.5047
# <info@packetgeneral.com <mailto:info@packetgeneral.com>>
#
# --Copyright Product--

# filename: serverg-install.sh
# This file checks the pre-requisites for ServerG and then installs it

SERVERG_PATH=/etc/serverg
LOG_DIR=/var/log/serverg
BIN_DIR=/usr/sbin
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$SERVERG_PATH:$PATH
SERVERG_FILE=/etc/serverg/serverg.conf
VAULT_PATH=/vault
export PATH
IFS='
'


##############################################################################
# on_exit	: This function will be called before exiting the shell script. It
#			deletes temporary files.
# Input		: None
# Output	: None
##############################################################################

on_exit()
{
	rm $tmpfile > /dev/null 2>&1
}


##############################################################################
# Main code starts here
##############################################################################

# Only root can run this
if [ "`id -u`" != "0" ]
then
        echo "You need to be root to run this script."
        exit 1
fi


# Register the function to be called befor exiting
trap on_exit EXIT

#Check if the package is installed
dpkg --status serverg > /dev/null 2>&1
if [ $? -eq 1 ]; then
	echo "Server-GENERAL debian package not installed"
	exit 1
fi

#Check if there are any configured repos
#If yes, fail the uninstall as no repo should be configured
grep -r "repo=" $SERVERG_FILE > /dev/null
if [ $? -eq 0 ]; then
        echo "Failed to uninstall Server-GENERAL: You need to remove all SG Profiles"
        exit 1
fi

#Remove the local keystore
key_type=`grep -r primary_key_loc $SERVERG_FILE | cut -f 2 -d '='`
if [ ! -z "$key_type" ]; then
        if [ $key_type = "local" ]; then
                location=`grep -r primary_path $SERVERG_FILE  | cut -f 2 -d '='`
                rm -rf $location > /dev/null 2>&1
        fi
fi

#
rm -rf $VAULT_PATH > /dev/null 2>&1
rm -rf $SERVERG_PATH > /dev/null 2>&1
rm -rf $LOG_DIR > /dev/null 2>&1
rm /etc/rc0.d/K99sg -rf > /dev/null 2>&1
rm /etc/rc6.d/K99sg -rf > /dev/null 2>&1
rm /etc/init.d/sgstop > /dev/null 2>&1

#TODO: Call license-remove

apt-get remove serverg
if [ $? -eq 1 ]; then
        echo "Failed to uninstall Server-GENERAL debian package"
        exit 1
fi

exit 0


