#!/bin/sh -x
# ISPsystem vdsreinstall

DetectFetch()
{
	if test -x /usr/bin/fetch; then
		fetch="/usr/bin/fetch -o "
	elif test -x /usr/bin/wget; then
		fetch="/usr/bin/wget -O "
	elif test -x /usr/bin/curl; then
		fetch="/usr/bin/curl -o "
	else
		echo "ERROR: no fetch program found."
		exit 1
	fi
}

DetectMd5()
{
	if test -x /sbin/md5; then
		md5="/sbin/md5 "
		isit=true
	elif test -x /usr/bin/md5sum; then
		md5="/usr/bin/md5sum "
		isit=false
	else
		echo "ERROR: no programm for checksum found."
		exit 1
	fi
}

DetectOS()
{
	kern=`uname -s`
	case "$kern" in
		FreeBSD)
			ver=`uname -r|sed -E 's/^([0-9]+\.[0-9]+).*$/\1/'`
			os="$kern-$ver"
			;;
		Darwin)
			os="Darwin"
			;;
		Linux)
			os="Linux-cc6"
			;;
		*)
			echo "Unknown OS type"
			exit 1
			;;
	esac
}

DetectArch()
{
	arch=`uname -m`
}

DetectFetch
DetectMd5

DetectOS
DetectArch

			
kern=`uname -s`
case "$kern" in
	FreeBSD)
		mgrname="VDSmanager-FreeBSD"
		;;
	Linux)
		mgrname="VDSmanager-Linux"
		;;
	*)
		echo "VDSmanager not available for this OS"
		exit 1
		;;
esac

tmpdir="/tmp/$mgrname"
mkdir -p $tmpdir
cd $tmpdir

mirror="download.ispsystem.com"

url="http://$mirror/$os/$arch/$mgrname/install.4.3.44.5.tgz"
archive="$tmpdir/install.tgz"

test -f $archive && rm -f $archive
$fetch $archive "$url"

if ! test -s $archive; then
	echo "Can't download $mgrname distribution"
	echo "Make sure it is available for your platform ($os $arch)"
	echo "List of supported distribution you can see at"
	echo "http://download.ispsystem.com/"
	rm -rf $tmpdir
	exit 1
fi

# check md5
$fetch $archive.md5 "$url.md5"

if test "$isit" = "true"; then
	remotesum=`cat $archive.md5 | awk '{print $4}'`
	localsum=`$md5 install.tgz | awk '{print $4}'`
else
	remotesum=`cat $archive.md5 | awk '{print $1}'`
	localsum=`$md5 install.tgz | awk '{print $1}'`
fi

if test "$localsum" != "$remotesum"; then
	echo "Invalid MD5 signature"
	echo "Please try again."
	rm -rf $tmpdir
	exit 1
fi

mgrdir="/usr/local/ispmgr/"
mkdir -p $mgrdir
cd $mgrdir
killall vdsmgr
tar xvzpf $archive 
rm -rf $tmpdir



