#!/bin/bash

CT_OSTEMPLATE="vzlinux-7-x86_64"
TEMPLATE_CPATH="/vz/template/vzlinux/7/x86_64/config/os/default"
MLISTS_F=$TEMPLATE_CPATH/mirrorlist
BURLS_F=$TEMPLATE_CPATH/repositories
YUMREPO="/etc/yum.repos.d/virtuozzo.repo"
VZPKG="/usr/sbin/vzpkg"
VZCTL="/usr/sbin/vzctl"
VZLIST="/usr/sbin/vzlist"
YUM="/usr/bin/yum"
UUIDGEN="/usr/bin/uuidgen"
GROUPS_INSTALL="vstorage-ui-backend"
PKGS_INSTALL="file"
PREMOVE="httpd"
CT_NAME="vstorage-ui"
CT_PARAMS="--ram 2G --diskspace 40G --name $CT_NAME"
ROOTPW=""
CT_IP=""
TARBALL=""
NAMESERVERS=""
BACKEND_BIN="/usr/libexec/vstorage-ui-backend/bin"
PROGNAME=`basename ${0}`
TMPDIR=`mktemp -d /tmp/${PROGNAME}_XXXXXX`

function cleanup() {
	umount $MLISTS_F >/dev/null 2>&1
	umount $BURLS_F >/dev/null 2>&1
	[ -d $TMPDIR ] && rm -rf $TMPDIR >/dev/null 2>&1
}

function error() {
	cleanup
	echo $*
	[ "x$CTID" = "x" ] && exit 1
	echo "Removing $CTID..."
	$VZCTL stop $CTID --fast >/dev/null 2>&1
	$VZCTL destroy $CTID >/dev/null 2>&1
	exit 1
}

function check_existance() {
	local b

	for b in $*; do
		[ -x $b ] && continue
		error "$b does not exist"
	done
}

function create_script() {
	local sdata=$1
	local tpath=$2

	echo -e $sdata > $tpath 2>/dev/null
	[ $? -ne 0 ] && error "Failed to create $tpath script"
	chmod 0755 $tpath >/dev/null 2>&1
	[ $? -ne 0 ] && error "failed to chmod $tpath script"
}

function replace_file() {
	local tfile=$1
	local tmpfile=$2
	local newurls=$3

	if [ -f $tfile -a ! -z "$newurls" ]; then
		cp $tfile $TMPDIR
		[ $? -ne 0 ] && error "Failed to prepare mirrorlists"
		for u in $newurls; do
			echo $u >> $tmpfile
			[ $? -ne 0 ] && error "Failed to add $u to $tfile"
		done
		mount -o bind $tmpfile $tfile
		[ $? -ne 0 ] && error "Failed to replace $tfile"
	fi
}

function exec_ct_cmd() {
	if [ "x$2" = "xverbose" ]; then
		$VZCTL exec $CTID $1
	else
		$VZCTL exec $CTID $1 >/dev/null 2>&1
	fi
	[ $? -ne 0 ] && error "Failed to exec $1 cmd inside $CTID"
}

function restore_tarball() {
	[ "x$TARBALL" = "x" ] && return
	local btar=`basename $TARBALL`
	echo "Restoring backup $TARBALL..."
	cp $TARBALL $VE_ROOT/$CTID/root/$btar > /dev/null 2>&1
	[ $? -ne 0 ] && error "Failed to copy $btar inside $CTID"
	exec_ct_cmd "$BACKEND_BIN/restore-management-node.sh -x venet0 -i venet0 -f /root/$btar" verbose
}

function usage() {
	echo "Usage: $0 (-p|--rootpw) PASSWORD (-i|--ip) IP [(-t|--tarball) TARBALL] [-n|--nameserver IP1,IP2]"
	cleanup
	exit 1
}

check_existance $VZPKG $VZCTL $UUIDGEN $YUM $VZLIST
[ ! -d $TMPDIR ] && error "Failed to create tmpdir!"

# Getopt
OPTS=$(getopt -o p:i:t:n: --long rootpw:,ip:,tarball:,nameserver: -- "$@")

eval set -- "$OPTS"

while true; do
	case $1 in
	   -p|--rootpw)
		ROOTPW="$2"
		shift 2
		;;
	   -i|--ip)
		CT_IP="$2"
		shift 2
		;;
	   -t|--tarball)
		TARBALL="$2"
		[ ! -f $TARBALL ] && error "Tarball $TARBALL not exists"
		shift 2
		;;
	   -n|--nameserver)
		NAMESERVERS=`echo $2 | sed "s,\,, ,g"`
		shift 2
		;;
	   --)
		break
		;;
	   *)
		echo "Invalid argument: $1" 1>&2
		exit 1
	esac
done

[ "x$ROOTPW" = "x" -o "x$CT_IP" = "x" ] && usage

# Get it from resolv.conf
[ "x$NAMESERVERS" = "x" ] && NAMESERVERS=`cat /etc/zresolv.conf 2>/dev/null | grep ^nameserver | sed "s,^nameserver ,,g"`

trap 'error "Terminating..."' 1 2 3 15

# Check that Ct with required name doe not exist
if [ "x$($VZLIST -H -o name -N $CT_NAME)" = "x$CT_NAME" ]; then
	echo "Container with name $CT_NAME already exists!.."
	echo
	$VZLIST -n -N $CT_NAME 2>/dev/null
	error ""
fi

# Generate ctid
CTID=`$UUIDGEN 2>/dev/null`
[ "x$CTID" = "x" ] && error "failed to generate CTID"

# 0. Do prevent template reinstall to avoid any user modifications
echo "Reinstalling $CT_OSTEMPLATE..."
$YUM reinstall $CT_OSTEMPLATE-ez -y >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to reinstall $CT_OSTEMPLATE"

# 1. Modify template config

# 1.1 Add virtuozzo URLs
echo "Updating $CT_OSTEMPLATE cache..."
replace_file $MLISTS_F $TMPDIR/mirrorlist "`cat $YUMREPO | grep ^mirrorlist | grep -v debug | sed "s,^mirrorlist=,,g"`"
replace_file $BURLS_F $TMPDIR/baseurl "`cat $YUMREPO | grep ^baseurl | grep -v debug | sed "s,^baseurl=,,g"`"

# 1.2 Update cache
$VZPKG update cache $CT_OSTEMPLATE >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to update $CT_OSTEMPLATE cache"

# 1.3 Create UI Container
echo "Creating $CTID..."
$VZCTL create $CTID --ostemplate $CT_OSTEMPLATE >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to create $CTID"

# Source ct config
CT_CONF="/etc/vz/conf/$CTID.conf"
. $CT_CONF

echo "Setting up $CTID..."
[ "x$CT_IP" != "x" ] && CT_PARAMS="$CT_PARAMS --ipadd $CT_IP"
[ "x$ROOTPW" != "x" ] && CT_PARAMS="$CT_PARAMS --userpasswd $ROOTPW"
for ns in $NAMESERVERS; do
	CT_PARAMS="$CT_PARAMS --nameserver $ns"
done
$VZCTL set $CTID $CT_PARAMS --save >/dev/null 2>&1
[ $? -ne 0 ] && error "failed to set $CT_PARAMS to $CTID"

create_script "#!/bin/bash\n
\n
FIREWALL_CMD=\"/usr/bin/firewall-cmd\"\n
FIREWALL_OFFLINE_CMD=\"/usr/bin/firewall-offline-cmd\"\n
AGENT_PORT=17514\n
\n
. \`dirname \$0\`/../ve.conf\n
\n
[ \"x\$IP_ADDRESS\" = \"x\" ] && exit 0\n
\n
if [ \"x\$1\" = \"x\" ]; then\n
\t    ACTION=\"add\"\n
elif [ \"\$1\" = \"--remove\" ]; then\n
\t    ACTION=\"remove\"\n
else\n
\t    exit 0\n
fi\n
\n
for ctip in \$IP_ADDRESS; do\n
\t    [ \"\${ctip#*:}\" = \"\${ctip}\" ] && ip=\"ipv4\" || ip=\"ipv6\"\n
\t    ARGS=\"--direct --\$ACTION-rule \$ip filter INPUT_direct 0 -i venet0 -s \$ctip -m tcp -p tcp --dport \$AGENT_PORT -j ACCEPT\"\n
\t    \$FIREWALL_CMD --permanent \$ARGS && \$FIREWALL_CMD --reload || \$FIREWALL_OFFLINE_CMD \$ARGS\n
done\n
\n
exit 0\n" $VE_PRIVATE/$CTID/scripts/premount

create_script "#!/bin/bash\n
\n
\`dirname \$0\`/premount --remove\n
\n
exit \$?\n" $VE_PRIVATE/$CTID/scripts/umount

echo "Starting $CTID..."
$VZCTL start $CTID --wait >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to start $CTID"

echo "Installing $GROUPS_INSTALL to $CTID..."
$VZPKG remove $CTID -p $PREMOVE >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to remove $PREMOVE"
$VZPKG install $CTID -p $PKGS_INSTALL >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to install $PKGS_INSTALL to $CTID"
$VZPKG install $CTID -g $GROUPS_INSTALL >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to install $GROUPS_INSTALL to $CTID"

exec_ct_cmd "PGSETUP_INITDB_OPTIONS=\"-E UTF8\" postgresql-setup initdb"
exec_ct_cmd "echo \"$ROOTPW\" | $BACKEND_BIN/configure-backend.sh -x venet0"
exec_ct_cmd "sed -e \"s,^configure_firewall\$,#configure_firewall,g\" -i $BACKEND_BIN/init-backend.sh"
exec_ct_cmd "$BACKEND_BIN/init-backend.sh"
exec_ct_cmd "sed -e \"s,^DefaultZone=.*,DefaultZone=trusted,g\" -i /etc/firewalld/firewalld.conf"
exec_ct_cmd "sed -e \"s,&& configure_firewall,,g\" -i $BACKEND_BIN/restore-management-node.sh"
exec_ct_cmd "sed -e \"s,validate_net_if ,/bin/true ,g\" -i $BACKEND_BIN/restore-management-node.sh"
cp $YUMREPO $VE_ROOT/$CTID/$YUMREPO >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to setup $YUMREPO for $CTID"

restore_tarball

$VZCTL restart $CTID >/dev/null 2>&1
[ $? -ne 0 ] && error "Failed to restart $CTID"

echo "All done!"
cleanup

exit 0
