#!/bin/bash 

#usage
function usage()
{
	echo "USAGE: pva-pp-postInstall [--nossl]" 1>&2
}

# create dummy service container that will proxy http requests to portal
function create_sve_proxy()
{
	IP_ADDRESS=`auto_assign_sve_address`

	echo "Create pp ve $PP_VE_PRIVATE $PP_INSTALL_DIR"

	INITDIR=`pwd`
	
	# Fix vzquota issue
	vzquota off $PP_VEID -f &> /dev/null 

	touch /etc/vz/dists/sve.conf || abort $? "Failed to create /etc/vz/dists/sve.conf"
	
	rm -rf $PP_VE_PRIVATE
	mkdir -p $PP_VE_PRIVATE/ || abort $? "Failed to create $PP_VE_PRIVATE/fs"
	mkvzfs $PP_VE_PRIVATE/fs || abort $? "Failed to create vzfs $PP_VE_PRIVATE/fs"
	mkdir -p $PP_VE_PRIVATE/scripts || abort $? "Failed to create $PP_VE_PRIVATE/scripts"
	ln -s  4 $PP_VE_PRIVATE/.ve.layout || abort $? "Failed to create $PP_VE_PRIVATE/.ve.layout"


	cp $PP_INSTALL_DIR/ve.conf $PP_VE_PRIVATE/ve.conf || abort $? "Failed to copy ve.conf"
	cp $PP_INSTALL_DIR/mount $PP_VE_PRIVATE/scripts/mount || abort $? "Failed to copy mount"
	vzctl register $PP_VE_PRIVATE $PP_VEID || abort $? "Failed to register $PP_VE_PRIVATE"

	# create /sbin 
	mkdir -p $PP_VE_PRIVATE/fs/root/sbin/ || abort $? "Failed to create $PP_VE_PRIVATE/fs/root/sbin/"
	cp $PP_INSTALL_DIR/init $PP_VE_PRIVATE/fs/root/sbin/init || abort $? "Failed to copy init"
	cd $PP_VE_PRIVATE/fs/root/sbin/
	ln init halt || { echo "Failed to create halt link";}
	ln init reboot || { echo "Failed to create reboot link";}

	# create /dev/null
	mkdir -p $PP_VE_PRIVATE/fs/root/dev || abort $? "Failed to create $PP_VE_PRIVATE/fs/root/dev"
	cd $PP_VE_PRIVATE/fs/root/dev
	mknod null c 1 3 || abort $? "Failed to create /dev/null"

	cd $INITDIR

	# set ip
	vzctl set $PP_VEID --ipadd $IP_ADDRESS --save || abort $? "Failed to assign IP address to Service Container"

	# Fix vzquota issue
	vzctl quotainit $PP_VEID

	vzctl start $PP_VEID || abort $? "Failed to start Service Container"
}

###################### Include common files #######################

. ${0/%pva-pp-*/pva-pp-functions.sh} || { echo "Failed to load hint functions"; exit -1;}

############################### Go  ##############################

echo "------------------------------------------------------------------------------------------------"
date "+%b %e %T PVA Power Panel postinstall configuration : start"

noSSL=

# parse options
eval set -- $* --
while true ; do
	case "$1" in
	    --help)		usage; exit 0 ;;
	    --nossl) 	noSSL="--nossl" ; shift ;;
	    --)		shift ; break ;;
	    *) 		shift ;;
	esac
done

postinstall $noSSL || abort $? "Power Panel postinstall configuration failed"

# create proxy sve
create_sve_proxy || abort $? "Failed to create Service Container"

date "+%b %e %T PVA Power Panel postinstall configuration : stop"
echo "------------------------------------------------------------------------------------------------"

exit 0

