#!/bin/bash

urlencode() {
    # Read the URL encoding in from the urlencode.sed file
    echo -n "$1" | tr '\n' '~' | sed \
        -e 's/%/%25/g' -e 's/ /%20/g' -e 's/ /%09/g' -e 's/!/%21/g' -e 's/"/%22/g' \
        -e 's/#/%23/g' -e 's/\$/%24/g' -e 's/\&/%26/g' -e 's/'\''/%27/g' -e 's/(/%28/g' \
        -e 's/)/%29/g' -e 's/\*/%2a/g' -e 's/+/%2b/g' -e 's/,/%2c/g' -e 's/-/%2d/g' \
        -e 's/\./%2e/g' -e 's/\//%2f/g' -e 's/:/%3a/g' -e 's/;/%3b/g' -e 's//%3e/g' \
        -e 's/?/%3f/g' -e 's/@/%40/g' -e 's/\[/%5b/g' -e 's/\\/%5c/g' -e 's/\]/%5d/g' \
        -e 's/\^/%5e/g' -e 's/_/%5f/g' -e 's/`/%60/g' -e 's/{/%7b/g' -e 's/|/%7c/g' \
        -e 's/}/%7d/g' -e 's/~/%7e/g' -e 's/      /%09/g'
}

ONLINE=$(wget.omg -q -O - http://installsrv.hq.ferrari-electronic.de/genlicense/test.html 2>/dev/null)
if [ ! "${ONLINE}" = "online" ]; then
    echo "no connection to licensing server"
    exit 2
fi
if [ "$HWTYPE" = "PCM" ]; then
    echo "Virtual Gate found"
    i2cserial="$sn"
    i2carticle="23104"
else
    i2cserial=$(i2cinfo -l | head -1 | cut -d ',' -f 6)
    i2carticle=$(i2cinfo -l | head -1 | cut -d ',' -f 7)
fi

if [[ ${i2cserial} != [0-9]* ]]; then
    echo "No serial number found. Run i2cconfig"
    exit
fi

if [ ${i2carticle} = "0" ];then
    echo "No article number found. Run i2cconfig"
    exit
fi

isQuadE1=$(lspci -n | grep -c "1011:f004")
if [ ${isQuadE1} -ge 1 ]; then
    if (dmidecode -s system-product-name | grep RX100 >/dev/null) ; then
        i2carticle=22114
    elif (dmidecode -s system-product-name | grep RX1330 >/dev/null) ; then
        i2carticle=22114
    elif (dmidecode -s system-product-name | grep RX200 >/dev/null) ; then
        i2carticle=22124
    elif (dmidecode -s system-product-name | grep DL360 >/dev/null) ; then
        i2carticle=22129
    elif (dmidecode -s system-product-name | grep DL120 >/dev/null) ; then
        i2carticle=22119
    elif (dmidecode -s system-product-name | grep DL320e >/dev/null) ; then
        i2carticle=22119
    else
    	i2carticle=22113
    fi
fi


isAtomBox=$(lspci -n | grep -c "1011:f005")
if [ ${isAtomBox} -ge 1 ]; then
    article=${i2carticle}
    serial=${i2cserial}
fi


TEMP=`getopt -o qhons:a:btxdk --long article,overwrite,noscan,demo,serial,help,ask,baseserial,scripttest,licensetest -n 'firstlic' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"
while true ; do
    case "$1" in
        -a|--article) article=$2
            shift 2
            ;;
        -b|--baseserial) baseserial=1
            shift 1
            ;;
        -n|--noscan) noscan=1
            shift
            ;;
        -d|--demo) demo=1
            shift
            ;;
        -s|--serial) serial=$2
            shift 2
            ;;
        -o|--overwrite) overwrite=1
            shift
            ;;
        -k|--keep) keepfiles=1
            shift
            ;;
        -q|--ask) ask=1
            shift
            ;;
        -x|--scripttest) scripttest=1
            shift
            ;;
        -t|--licensetest) licensetest=1
            shift
            ;;
        -h|--help)
            echo "Usage: firstlic [-s | --serial] [-a | --article] [-n | --noscan] [-o | --overwrite] [-d | --demo] [-k | --keep] [-q | --ask] [-b|--baseserial] [-t|--licensetest] [-x|--scripttest]"
            exit
            ;;

        --) shift
            break
            ;;
        *)
            echo "Internal error!"
            exit 1
            ;;
    esac
done

if [ -z "${article}" ]; then
    if [ ! -z "${ask}" ]; then
        unset article
        while [ -z "${article}" ]; do
	    read -p "Articlenumber[${i2carticle}]? " article
	    if [ -z "${article}" ]; then
	        article=${i2carticle}
	    fi
	    if [[ ${article} != [0-9]* ]]; then
	        echo "Number please"
	        article=""
	    fi	
        done
    else
        article=${i2carticle}
    fi
fi

if [ -z "${serial}" ]; then
    if [ ! -z "${ask}" ]; then
        unset serial
        while [ -z "${serial}" ]; do
	    read -p "Serial number [${i2cserial}]? " serial
	    if [ -z "${serial}" ]; then
	        serial=$i2cserial
	    fi
	    if [[ ${serial} != [0-9]* ]]; then
	        echo "Number please"
	        serial=""
	    fi	
        done
    else
        serial=$i2cserial
    fi
fi

if [ -z "${noscan}" ]; then
    if [ "$HWTYPE" = "PCM" ]; then
	info="Virtual Gate,04,00,a0,$sn,$sn,23104,60,2,OMGVM::PCM,04,00,a0,$sn,$sn,23104,60,2,OMGVM"
    else
    	echo "Scanning for cards ..."
    	info=$(i2cinfo -l)
    	if [ -z "${info}" ]; then
	    echo "No i2cinfo"
	    exit 1
    	fi
    fi
    encoded=$(urlencode "${info}")
else
    info=""
    encoded=''
fi

if [ -z "${article}"  -a  -z "${info}" ]; then
    echo "Error: -s not given and no article number selected"
    exit 2
fi


if [ "$(find /data  -maxdepth 0 -name '*.flf')" != "" ] || [ "$(find /data  -maxdepth 0 -name '*.fle')" != "" ] && [ "${overwrite}" != "1" ] ;then
    echo "Error: Found License file(s) and -o was not given"
    exit
fi

echo "Requesting license ..."
rm -f genlicense.err license.tar

par=""
if [ ! -z "${article}" ] ;then
    par="a=${article}"
fi

if [ ! -z "${serial}" ] ;then
    par="${par}&s=${serial}"
fi

if [ ! -z "${baseserial}" ] ;then
    baseserial=$(licinfo -d -w | grep SerialCode | sed 's/0SerialCode:s:+:\(.*\):/\1/')
    par="${par}&b=${baseserial}"
fi

if [ ! -z "${demo}" ] ;then
    demoserial=$(licinfo -d -w | grep SerialCode | sed 's/0SerialCode:s:+:\(.*\):/\1/')
    par="${par}&d=${demoserial}"
fi

if [ ! -z "${licensetest}" ] ;then
    par="${par}&t=1"
fi

if [ ! -z "${encoded}" ] ;then
    par="${par}&i=${encoded}"
fi

if [ -z "${scripttest}" ] ;then
    url="http://installsrv.hq.ferrari-electronic.de/genlicense/genlicense.php"
else
    url="http://installsrv.hq.ferrari-electronic.de/genlicense/g.php"
fi

echo "wget.omg -q -N --timeout=10 --tries=1 --content-disposition ${url}?${par}"
wget.omg -q -N --timeout=10 --tries=1 --content-disposition ${url}?${par}

rc=$?
if [ ${rc} -ne 0 ]; then
    case ${rc} in
	
        1) f="I'm perplexed";;
        2) f="Parse error";;
	3) f="File I/O error";;
	4) f="Network failure";;
	5) f="SSL verification failure";;
	6) f="Username/password authentication failure";;
	7) f="Protocol errors";;
	8) f="Server issued an error response";;
    esac
    echo "Request failed: ${f}"
    exit 1
fi

if [ -e genlicense.err ] ; then
    echo " failed:"
    echo ""
    cat genlicense.err
fi


if [ -e license.tar ]; then
    if [ -z "${demo}" -a -z "${keepfiles}" ]; then
    	# loesche alles aus data
   	rm -rf /data/*.fl[ef]
    fi
    echo "Unpacking ..."
    tar -C /data --no-same-owner -xf license.tar
    rm -f license.tar
    # Show what we've requested
    licinfo -d
fi
echo ""
