#!/bin/sh


#set -x

LMPATH=/usr/sbin
SYSTEMCTL=/bin/systemctl

DO_HBF=NoThanks
DO_HOSTCHECK=YesPlease
DO_RESTART=YesPlease

LIC_DIR=/etc/ifax

if [ -x $LMPATH/lmhostid ]
then
    HOSTID=$($LMPATH/lmhostid -n | sed -e 's/"\(............\) .*"/\1/')
fi

while [ -n "$1" ]
do
	case "$1" in
		--sr140)
			PART=sr140
			;;
		--hbf)
			PART=hbf
			;;
		--no-hosts)
			DO_HOSTCHECK=NoThanks
			;;
		--no-restart)
			DO_RESTART=NoThanks
			;;
		--with-licdir)
			shift
			LIC_DIR="$1"
			;;
		--with-hostid)
			shift
			HOSTID="$1"
			;;
		--with-part)
			shift
			PART="$1"
			;;
		--lmgrd-port)
			shift
			case $1 in
				''|*[!0-9]]*)
					echo "Invalid lmgrd-port; not a number: $1" >&2
					;;
				*)
					if [ "$1" -lt 1024 ]
					then
						echo "Invalid lmgrd-port; must be greater than 1023: $1" >&2
					elif [ "$1" -gt 65535 ]
					then
						echo "Invalid lmgrd-port; must be smaller than 65536: $1" >&2
					else
						LMGRD_PORT="$1"
					fi
					;;
			esac
			;;
		--vendor-port)
			shift
			case $1 in
				''|*[!0-9]]*)
					echo "Invalid vendor-port; not a number: $1" >&2
					;;
				*)
					if [ "$1" -lt 1024 ]
					then
						echo "Invalid vendor-port; must be greater than 1023: $1" >&2
					elif [ "$1" -gt 65535 ]
					then
						echo "Invalid vendor-port; must be smaller than 65536: $1" >&2
					else
						VENDOR_PORT="$1"
					fi
					;;
			esac
			;;
		--*)
			echo "Unknown option: $1" >&2
			;;
		*)
			SERIAL="$1"
			break;
			;;
	esac
	shift;
done

if [ -z "$HOSTID" ]
then
    echo "It is not possible to obtain a license without a host id."
    if [ ! -x $LMPATH/lmhostid ]
    then
	echo "Install the ifax-lmgrd package and rerun this program."
    fi
    exit 4
fi

if [ "$IGNORE_NOT_ROOT" != "YesPlease" ] && [ `id -u` -ne 0 ]
then
	echo "You must be root to execute this program."
	exit 3
fi

HOSTNAME=`hostname`
IPADDRESS=127.0.1.1

if [ "$DO_HOSTCHECK" = "YesPlease" ]
then
    ping -c 1 $HOSTNAME >/dev/null 2>&1
    if [ $? = 2 ]; then
	    echo "Warning! $HOSTNAME can't be resolved to an IP address!"
	    echo "The licensing server won't work until you fix this."
	    echo ""
	    echo "Do you want me to add the following line to /etc/hosts:"
	    echo "    $IPADDRESS		$HOSTNAME"
	    echo ""

	    printf '\nAdd the line [Y/n]? '
	    read response
	    case $response in
		    Y|y|"")
			    echo "$IPADDRESS		$HOSTNAME" >> /etc/hosts
			    echo "Added $HOSTNAME to /etc/hosts"
			    break
			    ;;
		    *)
			    echo "Rerun register when this problem is fixed"
			    exit 2
			    ;;
	    esac
    fi
fi

while [ -z "$SERIAL" ]
do
	printf "Please enter your serial number: "
	read SERIAL
	case "$SERIAL" in
		????-????-????-????-????|????-????-????-????|????????????????)
			echo "This serial looks valid";
			;;
		*)
			echo "This serial is invalid";
			echo "Please try again"
			echo ""
			continue;
	esac

	printf '\nYou entered "%s"\n\nIs this correct [Y/n]? ' "$SERIAL"
	read response
	case $response in
		Y|y|"")
			echo "Continuing... with $SERIAL"
			break;
			;;
		*)
			SERIAL=
			continue
			;;
	esac
done


fetch_licence ()
{
    serial="$1";
    hostid="$2";
    product="$3";
    echo "Activating licence for $SERIAL" >&2

    curl -s -f -d "serial=$serial&mac=$hostid" https://activate.ifax.com/product/$product
    case $? in
	0)
	    ;;
	5)
	    echo "ERROR: Unable to resolve proxy. Check HTTP proxy configuration."
	    ;;
	6)
	    echo "ERROR: Unable to resolve activation host. Check DNS settings."
	    ;;
	7)
	    echo "ERROR: Unable to connect to activation server. Check network/firewall settings."
	    ;;
	22)
	    echo "ERROR: Server error processing the activation request."
	    ;;
	52)
	    echo "ERROR: The activation server didn't reply anything. Try a second time and if it still fails, contact iFAX support."
	    ;;
	*)
	    echo "ERROR: Unknown error #$?."
	    ;;
    esac
}

#HOSTID=123456789012

LIC=$(fetch_licence "$SERIAL" "$HOSTID" "$PART")


printf 'Checking: "%s"\n' "${LIC:0:2}"

case ${LIC:0:2} in
    "OK")
	echo "Received a good licence";
	#echo "===================================================================="
	#echo "${LIC:3}"
	#echo "===================================================================="
	;;
    *)
    	echo "Bad Licence:";
	echo "$LIC"
	exit 1
	;;
esac

TMPLIC="$LIC_DIR/ifax-$SERIAL-$HOSTID-$$.tmp"

echo "${LIC:3}" > $TMPLIC


## WHen we read here, we read with options to
## 1) PRevent IFS whitespace collapsing
## 3) Prevent the \ at th eend from being an input continuation
exec 3>/dev/null
cat $TMPLIC | while IFS=. read -r LINE
do
    case "$LINE" in
    	'###FILE: '*)
	    echo "Saving ${LINE:9}"
	    exec 3>"$LIC_DIR/${LINE:9}"
	    ;;
	'SERVER this_host '????????????)
	    if [ -n "$LMGRD_PORT" ]
	    then
		echo "$LINE $LMGRD_PORT" >&3
	    else
		echo "$LINE" >&3
	    fi
	    ;;
	'VENDOR ifax')
	    if [ -n "$VENDOR_PORT" ]
	    then
		echo "$LINE PORT=$VENDOR_PORT" >&3
	    else
		echo "$LINE" >&3
	    fi
	    ;;
	*)  echo "$LINE" >&3
	    ;;
    esac

done
    exec 3>/dev/null

grep -s "^\(INCREMENT\|FEATURE\) [a-zA-Z]\+ ifax [0-9.]\+ permanent " $TMPLIC |sed -e 's/ *ifax.*permanent .*//' | while read type
do
    # This contain a permanent licence, move DEMO licences to backup area
    mkdir -p $LIC_DIR/demos
    if [ "$type" = "INCREMENT FaxGetty" ]
    then
	for f in $LIC_DIR/sr140*.key
	do
	    grep -q -s "^FEATURE SR140-DEMO" $f
	    if [ $? -eq 0 ]
	    then
		mv -f $f $LIC_DIR/demos
	    fi
	done
    fi
    for f in $LIC_DIR/ifax*.lic
    do
	grep -q -s "^$type ifax [0-9.]\+ [0-9]" $f
	if [ $? -eq 0 ]
	then
	    mv -f $f $LIC_DIR/demos
	fi
    done
done
rm $TMPLIC


if [ -x $LMPATH/lmreread ] && [ "$DO_RESTART" = "YesPlease" ]
then
    echo "Trying to reload licences:"
    $LMPATH/lmreread > /dev/null 2>&1
    if [ $? != 0 ]
    then
	echo "Starting licence manager:"
	$SYSTEMCTL restart ifax-lmgrd
    fi
    sleep 1;
    $LMPATH/lmstat -a
fi
