#!/bin/sh
# $Id$
#
# Script:	install_lic
#
# Author:	(c) High-Availability.Com Ltd
#
# Platform:	Unix
#
# Description:	Read the licence string in and place into correct file
#
. /opt/HAC/bin/rsf.sh

hostid=`${COMPANY_BIN}/hac_hostid`

LICDIR="${PRODUCT_ETC}"
LICFILE="${LICDIR}/license.`${COMPANY_BIN}/hac_hostid`"
LICENCE="${COMPANY_DIR}/.license"
LICENCE_SRV="secure.${COMPANY_DOMAIN}"
LICENCE_CONTACT="Please contact "${COMPANY_NAME}" (licensing@"${COMPANY_DOMAIN}") for licensing options."

#### more below the functions!!!!! ##############


################## Functions  ###################

# delay for presenting info to user
#
delay()
{
    sleep 1
}

#gets a web page
#params
# $2 is the server name/IP
# $3 URL to get
# $4 HTTP/1.1 etc
# $5 server's virtual name
webget()
{
    systype

    echo "GET ${3} ${4}" > /tmp/webget$$
    echo "${5}" >> /tmp/webget$$
    echo "${6}" >> /tmp/webget$$

    case "${COMPANY_OS}" in
	'hp-ux')
	    _nc="${COMPANY_BIN}/nc"
	    _ncargs="-w 5 ${2} 80"
	    ;;
	'linux')
	    _nc="${COMPANY_BIN}/nc"
	    _ncargs="-w 5 ${2} 80"
	    ;;
	'sunos')
	    _nc="${COMPANY_BIN}/nc"
	    _ncargs="-w 5 ${2} 80"
	    echo "" >> /tmp/webget$$
	    echo "EOF" >> /tmp/webget$$
	    ;;
    esac

    if [ "${4}" != "" ] ; then
	printf "  Connecting ..."

	res=`cat /tmp/webget$$ | eval ${_nc} ${_ncargs} > /tmp/w$$ 2> /dev/null`
	echo '  Done'
	echo $$ > /tmp/ww${1}
	rm -f /tmp/webget$$

	return 0
    else
	res=`echo "GET ${3}" | eval ${_nc} ${_ncargs}`
	rm -f /tmp/webget$$
	return ${res}
    fi
}

# get_interfaces
# - get a list of interfaces
# arg 1 is a list of interfaces to not bother configuring

get_interfaces()
{
    already=${1}
    
    filter=`echo ${1} | awk 'BEGIN {
	n = 1;
	result = "";
    }
    { while( $n ) {
	    result = result "|" $n;
	    n ++ ;
	}
    }
    END { print result; }'`
    
    case "${COMPANY_OS}" in
	'linux')
	    remove_from_top=3
	    zap="lo lo0"
	    ;;
	'hp-ux')
	    netstat -in | grep -v Name | awk '{print $1}' | grep -v :
	    ;;
	*)
	    remove_from_top=2
	    zap="lo lo0"
	    netstat -in | grep -v Name | grep e | awk '{print $1}' | grep -v :
	    ;;
    esac

}

# get_ifs_mac
# - find the mac address for a given interface
# args: interface name

get_ifs_mac()
{
    ifs="${1}"

    if [ "${COMPANY_OS}" = "hp-ux" ]; then
	{
	    if [ -x /usr/sbin/lanscan ]; then
		_lanscan=/usr/sbin/lanscan
	    else
		echo "none"
		return
	    fi
	}
    else
	{
	    if [ -x /sbin/ifconfig ]; then
		_ifconfig=/sbin/ifconfig
	    fi
	    
	    if [ -x /usr/sbin/ifconfig ]; then
		_ifconfig=/usr/sbin/ifconfig
	    fi

	    ifscfg=`${_ifconfig} ${ifs}`

	    if [ $? -ne 0 ]; then
		echo "none"
		return
	    fi
	}
    fi

    mac="none"

    case "${COMPANY_OS}" in
	'sunos')
	    mac=`${_ifconfig} ${ifs} | awk '/ether/ { print $2; }'`
	    ;;
	'darwin')
	    mac=`${_ifconfig} ${ifs} | awk '/ether/ { print $2; }'`
	    ;;
	'linux')
	    mac=`${_ifconfig} ${ifs} | awk '/HWaddr/ { print $5; }'`
	    ;;
	'hp-ux')
	    mac=`${_lanscan} | grep ${ifs} | awk '{print $2}'`
	    ;;
	'aix')
	    mac=`netstat -v | grep Hardware | awk '{print $3}'`
    esac

    echo ${mac} | tr '[a-f]' '[A-F]'
}

# Function: get_licence_serial 
# $1 is the serial number - 0 for demo
get_licence_serial()
{

    ifnm=`get_interfaces | awk '{print $1;}'`
    ifmac=`get_ifs_mac ${ifnm} | awk '{print $1;}'`
    ifmac=`echo ${ifmac} | tr -d ':'`
    query="/licence.php?prod=${PRODUCT_NAME}&mac=${ifmac}&serial=$1&hostid=${hostid}&os=${COMPANY_OS}&arch=${COMPANY_ARCH} HTTP/1.1 Host:${LICENCE_SRV}"
    webget $$ ${LICENCE_SRV} ${query} 2> /dev/null
    result=`cat /tmp/ww$$`
    rm /tmp/ww$$

    if [ "${result}" -eq "0" ];then
        license=`echo ${result} | sed -n 's#^.*<lic>\(.*\)</lic>.*$#\1#p'`
        message=`echo ${result} | sed -n 's#^.*<msg>\(.*\)</msg>.*$#\1#p'`
    elif [ "${result}" -gt "0" ] ; then
        license=`cat /tmp/w${result} | sed -n 's#^.*<lic>\(.*\)</lic>.*$#\1#p'`
        message=`cat /tmp/w${result} | sed -n 's#^.*<msg>\(.*\)</msg>.*$#\1#p'`
        rm /tmp/w${result}
    else
        license=""
        message="  Unable to contact ${LICENCE_SRV}"
    fi
}


# Function: get_licence
# $1 is the diag file name
get_licence()
{
 
    printf "Do you already have a licence string? (y/n): "
    xor n y n
    if [ $? -ne 0 ]; then
        printf "Have you been provided with a serial number by ${COMPANY_NAME}? (y/n): "
        xor n y n
        if [ $? -ne 0 ]; then
            printf "Do you want to obtain a DEMO licence? (requires web/http access) (y/n): "
            xor n y n
            if [ $? -ne 0 ]; then
                        echo "  ${LICENCE_CONTACT}"
                        return 1
            else
                        get_licence_serial 0
            fi
        else
            printf "Enter your serial number: "
            read serial
            get_licence_serial ${serial}
        fi
    
        #print any message returned from server/get_licence
        echo ${message}
    
        if [ "${license}" = "" ]; then
            echo "  Unable to automaticly obtain a licence"
            echo "  ${LICENCE_CONTACT}"
            return 1
        fi
    else
    
  	echo
   	echo "  ---+---   ---+---   ---+---  ---+---  ---+---   ---+---   ---+---";
   	echo
   	echo "  You will now be prompted for your licence string which may consist"
   	echo "  of a single 24 byte string of alphabetic, punctuation and numeric"
   	echo "  characters consisting of both upper and lower case. This must be"
   	echo "  entered exactly as given."
   	echo
   	echo "  Your licence certificate also contains a verification string to"
   	echo "  highlight if a character is [L]owercase, [U]ppercase, [P]unctuation"
   	echo "  or [D]ecimal."
   	echo
   	echo "  To abort this program, respond to the next question with 'q'."
   	echo 
   	echo     "                          [                        ]"
   	printf "Enter your licence string: "
   	read license
        
   	if [ "${license}" = "q" -o "${license}" = "Q" ]; then
      	    return 1
   	fi
    fi
       
 

    return 0
}


add_licence()
{
   LICENSED=1 		# 1 = not licensed.
   echo

   if [ -f "${LICFILE}" ];then
   	eval ${PRODUCT_BIN}/${PRODUCT_BINARY} -v 2>/dev/zero
   	if [ $? -eq 0 ]; then
   		LICENSED=0	# 0 = licensed
   		echo "  Licence for ${PRODUCT} already installed"
   		echo
   		echo "  Details"
   		echo
   		2>&1 ${PRODUCT_BIN}/${PRODUCT_BINARY} -v | awk '{printf("\t%s\n",$0)}' | grep -v "Copyright"
   
   		printf "\n        %-16s %-12s %s\n" "Hostname"  "hac_hostid" "Licence String"
   		echo "        ---------------- ------------ ------------------------"
   		printf "        %-16s %-12s %s\n" `hostname` ${hostid} `cat ${LICFILE}`
   
   		echo
   		printf "Do you want to install a new licence? (y/n): "
   		xor n y n
   
   		if [ $? -eq 1 ]
   		then
   			echo
   			return 0
   		fi
   	else
   		echo "  Invalid licence for ${PRODUCT} found in ${LICFILE}"
   	fi
   	
   fi
   
   if [ ${LICENSED} -eq 1 ]; then
   
   	echo
   	echo "  You will need a licence for ${PRODUCT} before you can use ${PRODUCT}."
   	echo "  If you have one and are ready to continue, enter y below;"
   	echo "  alternatively, contact your vendor to request a licence string."
   	
   	printf "Ready to install licence (y/n)? "
   	xor n y n
   	
   	if [ $? -eq 1 ]; then
   		echo "  Ok, run \"hac_install_lic ${PRODUCT_PREFIX}\" when you have a valid licence."
   		return 1
   	fi
   fi
   
   LICENSED=1
   while [ ${LICENSED} -gt 0 ]; do    
      	get_licence
 	if [ $? -eq 0 ]; then
    		if [ -f "${LICFILE}" ]; then
    		    echo
			echo "  Moving existing licence file to ${LICFILE}.bak"
			mv ${LICFILE} ${LICFILE}.bak
			moved_licfile=1
    		fi
    		
    		echo ${license} > ${LICFILE}
    		echo "  Licence installed in ${LICFILE}"
    		echo "  Running ${PRODUCT_BINARY} -v to verify:"
    		eval ${PRODUCT_BIN}/${PRODUCT_BINARY} -v 2> /dev/null
    		LICENSED=$?
    		
    		if [ ${LICENSED} -eq 0 ]; then
    		    echo
    		    echo "  ${PRODUCT} licence has been successfully installed and verified."
    		    echo
    		    return 0
    		else
    		    echo
    		    echo "  *** Invalid licence *** Please try again."
    		    echo
 			if [ -f "${LICFILE}.bak" -a ${moved_licfile} -eq 1 ]; then
    			   echo "  Restoring backup of old licence file."
    			   echo
    			   mv ${LICFILE}.bak ${LICFILE}
    		    fi
    		fi
    	else
    		## no lic
    		echo
    		echo "  *** No licence String has been obtained ***"
    		echo
        fi
    	   
    	   
    	   
    	if [ ${LICENSED} -eq 0 ];then
    	    break
    	fi
    	
    	printf "Do you want to try again (y/n)? "
    	xor n y n
    	
    	if [ $? -eq 1 ]; then
    	    break
    	fi
       
   done
   
   if [ ${LICENSED} -gt 0 ]; then
   	return 1
   fi
   
   return ${LICENSED}
}


############################# end of functions ######

# display licence agreement, if any
if [ -f "${LICENCE}" ]; then
        more "${LICENCE}"
        printf "Do you accept the terms of this agreement? (y/n): "
        xor n y n
        if [ $? -ne 0 ]; then
                echo "  Aborting licensing."
                echo "  Please uninstall this software and return any media to"
                echo "  the place where you obtained it for a refund."
                exit 1
        fi
fi

#check licence dir exists - possibly install problem
if [ ! -d "${LICDIR}" ]; then
    echo "  *** Unable to create licence file in ${LICDIR} ***"
    exit 1
fi


add_licence
