#!/bin/sh
# ISPsystem install 

Usage()
{
	cat << EOU >&2

Usage:
	$0 --help 	Print this help

	$0 [options] [mgrname]
	--os OS		Force use OS distribution
	--arch ARCH	Force use ARCH architecture
	--ip IP		Use IP for licence check
	
EOU
}

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
}

DetectOS()
{
	kern=`uname -s`
	case "$kern" in
		FreeBSD)
			ver=`uname -r|sed -E 's/^([0-9]+\.[0-9]+).*$/\1/'`
			os="$kern-$ver"
			;;
		Linux)
			if test -f "/etc/debian_version"; then
				ver=`cat /etc/debian_version`
				os="Debian-$ver"
			elif test -f "/etc/redhat-release"; then
				distname=`cat /etc/redhat-release| sed -e 's/\s.*$//'`
				ver=`cat /etc/redhat-release| sed -r 's/[^0-9]+([0-9]+).*$/\1/'` 
				os="$distname-$ver"
			else
				if test -e "/usr/lib/libstdc++.so.7"; then
					os="Linux-cc7"
				elif test -e "/usr/lib/libstdc++.so.6"; then
					os="Linux-cc6"
				else
					os="Linux-cc5"
				fi	
			fi
			;;
		*)
			echo "Unknown OS type"
			exit 1
			;;
	esac
}

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

echo
echo "ISPsystem install v.2.0"
echo

while true
do
	case "$1" in 
		-h | --help)
			Usage
			exit 0
			;;
		--os)
			os=${2:-.}
			shift 2
			;;
		--arch)
			arch=${2:-.}
			shift 2
			;;
		--ip)
			ip=${2:-.}
			ipparam="ip=$ip"
			shift 2
			;;
		-*)
			echo Unrecognized flag : "$1" >&2
			Usage
			exit 1
			;;
		*)
			break ;;
	esac
done

DetectFetch

if test "$os" = ""; then
	DetectOS
fi

if test "$arch" = ""; then
	DetectArch
fi

if test $# -eq 0 ; then
	# choose manager
	list=`$fetch - -q "http://lic.ispsystem.com/liclist.cgi?$ipparam"`
	
	if test "$list" = "no_license_found"; then
		echo "You have no active licenses"
		exit 1
	fi

	while true 
	do
		j="1"
		for i in $list; do
			echo "$j) $i"
			eval "mgrval$j=$i"
			j=$(($j+1))
		done
	
		echo "0) Exit"
		echo
		read -p "Please choose software to install: " n
		echo
		
		if test "$n" = "0"; then
			exit 0
		fi
	
		eval mgrname=\$mgrval$n
		if test "$mgrname" != ""; then
			break;
		fi
	done
else
	mgrname=$1
fi

url="http://download.ispsystem.com/$os/$arch/$mgrname/install.4.2.tgz"

archive="/tmp/$mgrname.tgz"

if test -x /usr/bin/ntpdate; then
	/usr/bin/ntpdate -b pool.ntp.org
fi

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

# XXX check md5

if ! test -s $archive; then
	echo "Can't download $mgrname distribution"
	echo "Make sure it is available for your platform ($os $arch)"
	exit 1
fi

mgrdir="/usr/local/ispmgr/"
test -d $mgrdir || mkdir -p $mgrdir
cd $mgrdir
tar xzpf $archive
rm -rf $archive

killall ispmgr
/usr/local/ispmgr/bin/ispmgr &


