#!/bin/sh
# Copyright (C) 2002 by SWsoft. All rights reserved.
#
# Script to prepair repair VE
#

# detect OS name
uname -s | grep FreeBSD 2>&1 > /dev/null
__FreeBSD__=$?

if [ $__FreeBSD__ = 0 ]; then
MOUNTCMD="mount_union"
else
MOUNTCMD="mount -n --bind"
# services that are on in repair VE
# two ssh[d]-keygen services due to some templates
# has renamed sshd-keygen service
SERVICEON="network rsyslog syslog ssh-keygen sshd-keygen xinetd"
fi

repairmount="/repair"
vzctl=/usr/sbin/vzctl

[ -f /etc/sysconfig/vz ] || exit 1
[ -f "$VE_CONFFILE" ] || exit 1

. /etc/sysconfig/vz
. $VE_CONFFILE

# get VEID of 'repaired' VE
REPAIRED=`echo $VE_TYPE | sed 's/repair://'`

[ -f /etc/sysconfig/vz-scripts/$REPAIRED.conf ] || exit 1

# gets VE_ROOT for repaired VE
# saves it and sets VE_ROOT
# for repair VE
oldve=$VEID
VEID=$REPAIRED
. /etc/sysconfig/vz
. /etc/sysconfig/vz-scripts/$REPAIRED.conf
VE_ROOTX=$VE_ROOT
VEID=$oldve
. /etc/sysconfig/vz
. $VE_CONFFILE

# checks that repaired VE is mounted if not
# tries to mount it and in case of failure
# exits with error
mount_repaired_ve()
{
	$vzctl --skiplock status $REPAIRED | grep -w "mounted" > /dev/null 2>&1
	[ $? -eq 0 ] && return

	$vzctl --skiplock mount $REPAIRED > /dev/null 2>&1
	[ $? -eq 0 ] && return

	echo "Could not mount private area for VE#$REPAIRED"
	exit 1
}

# mount repaired VE inside repair VE
mount_repaired_to_repair()
{
	mkdir -p "$VE_ROOT/$repairmount"
	$MOUNTCMD $VE_ROOTX "$VE_ROOT/$repairmount"
	if [ $? -ne 0 ]; then
	    echo "Can't mount repaired VE inside repair"
	    exit 1
	fi
}

CHKCONFIG=/sbin/chkconfig

# set all services in 'off' except some predifined  
set_services()
{
	[ -f $VE_ROOT/sbin/chkconfig ] \
		|| return;	# skip services setting

	# CHROOT's is safety in this place, cause repair VE is clear on creation
	# and theoritically should be mounted read-only
	local serv_list=`chroot $VE_ROOT /sbin/chkconfig --list | grep "0:" | awk '{ print $1 }'`
	if [ $? -ne 0 ]; then
		echo "Could not get list of services"
		exit 1
	fi

	# check 
	XINETD_SSH=`chroot $VE_ROOT /sbin/chkconfig --list ssh 2>/dev/null | grep -e 'ssh' | sed 's|:||' | awk '{print \$2}'`
	if [ "$XINETD_SSH" = "on" ]; then
		: # ssh is aenables through xinetd
	else
		# enable sshd 
		SERVICEON="sshd $SERVICEON"
	fi	

	# turn off all services
	local dir
	for dir in $serv_list; do
		chroot $VE_ROOT /sbin/chkconfig --del $dir 
	done

	# turn on predefined
	for dir in $SERVICEON; do
		chroot $VE_ROOT /sbin/chkconfig --add $dir 		
	done
}

# # doing remount repair VE read-only
# function remount_repair()
# {
# 	options="$TEMPLATE:$VE_PRIVATE,ro"
# 	set +e
# 	umount $VE_ROOT
# 	mount -n -t vzfs -o $options none $VE_ROOT
# 	set -e
# }

function copy_ugm()
{
	for file in /etc/passwd /etc/shadow /etc/group ; do
		cp -a $VE_ROOT/$repairmount/$file $VE_ROOT/$file
	done
}

if [ $__FreeBSD__ != 0 ]; then
	set_services
fi

#remount_repair
mount_repaired_ve
mount_repaired_to_repair
copy_ugm

exit 0

