#!/bin/bash
#
# chkconfig: 356 95 5
# description: prepare omg

### BEGIN INIT INFO
# Provides: omgsetup
# Required-Start: $network $local_fs $remote_fs 
# Required-Stop: $network $local_fs $remote_fs
# Should-Start: $syslog $named
# Should-Stop: $syslog $named
# Short-Description: start and stop omgsetup
# Description: prepare omg
### END INIT INFO

lockfile=/var/lock/subsys/omg

>/tmp/cmdline

echo "$0 start: $(date)" >> /tmp/sequence

#
# Setup for Box
#

#
# some inits
#

S2M=FAIL
S2MSERNUM=unknown
sn=99999
CHANNELS=0
HWFOUND=0
# color => new RH6.0 bootup
# verbose => old-style bootup
# anything else => new style bootup without ANSI colors or positioning
BOOTUP=color
# column to start "[  OK  ]" label in 
RES_COL=60
# terminal sequence to move to that column. You could change this
# to something like "tput hpa ${RES_COL}" if your terminal supports it
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
# terminal sequence to set color to a 'success' color (currently: green)
SETCOLOR_SUCCESS="echo -en \\033[0;32m"
# terminal sequence to set color to a 'failure' color (currently: red)
SETCOLOR_FAILURE="echo -en \\033[0;31m"
# terminal sequence to set color to a 'warning' color (currently: yellow)
SETCOLOR_WARNING="echo -en \\033[0;33m"
# terminal sequence to reset to the default color.
SETCOLOR_NORMAL="echo -en \\033[0;39m"

echo_success() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
  echo -n $"  OK  "
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 0
}
echo_failure() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo -n $"FAILED"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 1
}

echo_info() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
  echo -n $" INFO "
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 1
}

echo_warning() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo -n $" WARN "
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 1
}

# The following line will be modified by mkdebian. Don't touch!
echo "export FEATUREVERSION=5" >> /tmp/cmdline

which checkmsc >/dev/null 2>&1 && checkmsc


if [ -e /tmp/logs ]; then
    rm -rf /tmp/logs
    ln -sf /var/log/omgweblog /tmp/logs 
fi
if [ ! -e /tmp/logs ]; then
    ln -sf /var/log/omgweblog /tmp/logs 
fi



touser () {
    echo "$@"
}
touserOk (){
    echo -n "$@"
	echo_success
	echo
}
touserFail (){
    echo -n "$@"
	echo_failure
	echo
}
touserWarn (){
    echo -n "$@"
	echo_warning
	echo
}
touserInfo (){
    echo -n "$@"
	echo_info
	echo
}

calclines() {
    echo $(i2ccalclines)
}

licenabled () {
    l=$(licinfo -M ${1} -t bool -n Enable)
    rc=$?
    if [ "${l}" = "TRUE" ] ; then
        return 0
    else
        return 1
    fi
}


getVMSernum () {
    c=99999

    #VMware
    s=$(dmidecode -t 1 | grep "Serial Number: VMware")
    if [ "x${s}" != "x" ] ; then
        a=$(dmidecode -t 1| grep -E "Serial Number: VMware|UUID" | md5sum)
        let b="0x${a:${#a}-9:6}";
        c=$(/usr/bin/padzeros ${b:1,4})
        let cn=10#$c+0
        export sn=$cn
        export SYSTEM="OMGVM${c}"
        export OMGVSYSTEM="OMGVM${c}"
        export OMGVSN=$cn
        export OMGDMISN="$(dmidecode -t 1| grep -E "Serial Number: VMware." | sed -e "s/.*Serial Number: VMware.//")"
        export OMGUUID="$(dmidecode -s system-uuid)"
        export OMGHOST="VMware"

        echo "export OMGVSN=\"${OMGVSN}\"" >> /tmp/cmdline
        echo "export OMGVSYSTEM=\"${OMGVSYSTEM}\"" >> /tmp/cmdline
        echo "export OMGDMISN=\"${OMGDMISN}\"" >> /tmp/cmdline
        echo "export OMGUUID=\"${OMGUUID}\"" >> /tmp/cmdline
        echo "export OMGHOST=\"${OMGHOST}\"" >> /tmp/cmdline

        return    
    fi

    s=$(dmidecode -t 1 | grep "Manufacturer: Microsoft Corporation")
    if [ "x${s}" != "x" ] ; then
        a=$(dmidecode -t 1 | grep -E "Serial Number:|UUID" | md5sum)
        let b="0x${a:${#a}-9:6}";
        c=$(/usr/bin/padzeros ${b:1,4})
        let cn=10#$c+0
        export sn=$cn
        export SYSTEM="OMGHV${c}"
        export OMGVSYSTEM="OMGHV${c}"
        export OMGVSN=$cn
        export OMGDMISN="$(dmidecode -t 1| grep -E "Serial Number:" | sed -e "s/.*Serial Number: //")"
        export OMGUUID="$(dmidecode -s system-uuid)"
        export OMGHOST="HyperV"

        echo "export OMGVSN=\"${OMGVSN}\"" >> /tmp/cmdline
        echo "export OMGVSYSTEM=\"${OMGVSYSTEM}\"" >> /tmp/cmdline
        echo "export OMGDMISN=\"${OMGDMISN}\"" >> /tmp/cmdline
        echo "export OMGUUID=\"${OMGUUID}\"" >> /tmp/cmdline
        echo "export OMGHOST=\"${OMGHOST}\"" >> /tmp/cmdline

        return    
    fi

    #VirtualBox
    s=$(dmidecode -s system-product-name)
    if [ "${s}" = "VirtualBox" ] ; then
        a=$(dmidecode -s system-uuid | md5sum)
        let b="0x${a:${#a}-9:6}";
        c=$(/usr/bin/padzeros ${b:1,4})
        let cn=10#$c+0
        export sn=$cn
        export SYSTEM="OMGVB${c}"
        export OMGVSYSTEM="OMGVB${c}"
        export OMGVSN=$cn
        export OMGDMISN="$(dmidecode -s system-uuid)"
        export OMGUUID="$(dmidecode -s system-uuid)"
        export OMGHOST="VirtualBox"

        echo "export OMGVSN=\"${OMGVSN}\"" >> /tmp/cmdline
        echo "export OMGVSYSTEM=\"${OMGVSYSTEM}\"" >> /tmp/cmdline
        echo "export OMGDMISN=\"${OMGDMISN}\"" >> /tmp/cmdline
        echo "export OMGUUID=\"${OMGUUID}\"" >> /tmp/cmdline
        echo "export OMGHOST=\"${OMGHOST}\"" >> /tmp/cmdline

        return    
    fi

    #KVM
    s=$(dmidecode -s system-product-name)
    if [ "${s}" = "Bochs" ] ; then
        a=$(dmidecode -s system-uuid | md5sum)
	if [ -z "${a}" ]; then
	    echo "No system-uuid found for kvm machine"
	    return
	fi
        let b="0x${a:${#a}-9:6}";
        c=$(/usr/bin/padzeros ${b:1,4})
        let cn=10#$c+0
        export sn=$cn
        export OMGVSYSTEM="OMGKV${c}"
        export SYSTEM="OMGKV${c}"
        export OMGVSN=$cn
        export OMGDMISN="$(dmidecode -s system-uuid)"
        export OMGUUID="$(dmidecode -s system-uuid)"
        export OMGHOST="KVM"

        echo "export OMGVSN=\"${OMGVSN}\"" >> /tmp/cmdline
        echo "export OMGVSYSTEM=\"${OMGVSYSTEM}\"" >> /tmp/cmdline
        echo "export OMGDMISN=\"${OMGDMISN}\"" >> /tmp/cmdline
        echo "export OMGUUID=\"${OMGUUID}\"" >> /tmp/cmdline
        echo "export OMGHOST=\"${OMGHOST}\"" >> /tmp/cmdline

        return    
    fi

    #for all other HW
    a=$(dmidecode -s system-uuid | md5sum)
    if [ -z "${a}" ]; then
	echo "No system-uuid found for machine"
	return
    fi
    let b="0x${a:${#a}-9:6}";
    c=$(/usr/bin/padzeros ${b:1,4})
    let cn=10#$c+0
    export sn=$cn
    export OMGVSYSTEM="OMGTR${c}"
    export SYSTEM="OMGTR${c}"
    export OMGVSN=$cn
    export OMGDMISN="$(dmidecode -s system-uuid)"
    export OMGUUID="$(dmidecode -s system-uuid)"
    export OMGHOST="HWTRUNK"

    echo "export OMGVSN=\"${OMGVSN}\"" >> /tmp/cmdline
    echo "export OMGVSYSTEM=\"${OMGVSYSTEM}\"" >> /tmp/cmdline
    echo "export OMGDMISN=\"${OMGDMISN}\"" >> /tmp/cmdline
    echo "export OMGUUID=\"${OMGUUID}\"" >> /tmp/cmdline
    echo "export OMGHOST=\"${OMGHOST}\"" >> /tmp/cmdline

    return    
}

chklicense () {
    export BOWL=1
    echo "export BOWL=1" >> /tmp/cmdline

    if  ! licinfo -d > /dev/null ; then
        echo "OMG: License file not found or corrupt"
        # Think
        return
    fi

    echo -n "OMG: "
    showlic

    if [ "${S2MID}" = "6" ] ; then
        if [ "x${HWTYPE}" = "xMGB" -o "x${HWTYPE}" = "xQUADE1" -o "x${HWTYPE}" = "xAtomBox" ] ; then
            let ld=0
            if  licenabled 43 ; then
                ld=$(($ld+$(licinfo -M 43 -t int -n MaxLines)))
            fi
            if  licenabled 44 ; then
                ld=$(($ld+$(licinfo -M 44 -t int -n MaxLines)))
            fi
            if  licenabled 47 ; then
                ld=$(($ld+$(licinfo -M 47 -t int -n MaxLines)))
            fi

            ln=$(licinfo -t string -M 46 -n HWSernum)

            found="false"
            for s in ${S2MSERNUM}; do
                if echo ${ln} | grep -q "${s}" ; then
                    found="true"
                    break
                fi
            done

            if [ ${found} = "false" ] ; then
                touserFail "OMG: License is not for this box ${S2MSERNUM} ${ln}"
                export CHANNELS=0
                export LDCHANNELS=0
                export LOMCHANNELS=0
                echo "export CHANNELS=${CHANNELS}" >> /tmp/cmdline
                echo "export LDCHANNELS=${LDCHANNELS}" >> /tmp/cmdline
                echo "export LOMCHANNELS=${LOMCHANNELS}" >> /tmp/cmdline
                return
            fi

            export hwsn=${S2MSERNUM}
            echo "export hwsn=\"${S2MSERNUM}\"" >> /tmp/cmdline

            export LDCHANNELS=$ld
            echo "export LDCHANNELS=$ld" >> /tmp/cmdline
            if licenabled 45 ; then
                ld=$(licinfo -M 45 -t int -n MaxLines)
                export LOMCHANNELS=${ld}
            else
                export LOMCHANNELS=0
            fi
            echo "export LOMCHANNELS=${LOMCHANNELS}" >> /tmp/cmdline

            CHANNELS=$(i2ccalclines)
        else
            ln=$(licinfo -t string -M 46 -n HWSernum)

            found="false"
            for s in ${S2MSERNUM}; do
                if echo ${ln} | grep -q "${s}" ; then
                    found="true"
                    break
                fi
            done

            if [ ${found} = "false" ] ; then
                touserFail "OMG: License is not for this box ${S2MSERNUM} ${ln}"
                export CHANNELS=0
                export LDCHANNELS=0
                export LOMCHANNELS=0
                echo "export CHANNELS=${CHANNELS}" >> /tmp/cmdline
                echo "export LDCHANNELS=${LDCHANNELS}" >> /tmp/cmdline
                echo "export LOMCHANNELS=${LOMCHANNELS}" >> /tmp/cmdline
                return
            fi

            export hwsn=${S2MSERNUM}
            echo "export hwsn=\"${S2MSERNUM}\"" >> /tmp/cmdline

            ld=$(licinfo -M 43 -t int -n MaxLines)
            CHANNELS=$(i2ccalclines)
            export LDCHANNELS=$ld
            echo "export LDCHANNELS=$ld" >> /tmp/cmdline
            if licenabled 45 ; then
                ld=$(licinfo -M 45 -t int -n MaxLines)
                export LOMCHANNELS=${ld}
            else
                export LOMCHANNELS=0
            fi
            echo "export LOMCHANNELS=${LOMCHANNELS}" >> /tmp/cmdline
        fi
    else
        # S0 Box

        hwsernum=$(i2crdhwserial | cut -d ' ' -f 1)
        rc=$?
        if [ ${rc} -eq 2 ]; then
            # Oups
            touserFail "OMG: Fatal error. Getting hwserial number failed, setting default"
            export hwsn="0"
        fi

        if [ -z ${hwsernum} ]; then
            # Mmh, Hamlet
            touserFail "OMG: No HWserial in eeprom found, setting default"
            export hwsn="0"
        fi

        if [ ${rc} -eq 1 ]; then
            touserFail "OMG: No hwserial in eeprom found, setting default"
            export hwsn="0"
        else
            export hwsn=${hwsernum}
        fi
        echo "export hwsn=${hwsn}" >> /tmp/cmdline

        lichwsn=$(licinfo -M 46 -t string -n HWSernum  | cut -d ' ' -f 1)
        if [ "${lichwsn}" != "${hwsn}" ] ; then
            touserFail "OMG: License is not for this box"
            hwsn=0 # usw
        fi

        if  ! licenabled 44 ; then
            touserFail "Base license not enabled"
            # Noch return mit entsprechenden Variablen
        fi
        ld=$(licinfo -M 44 -t int -n MaxLines)
        export CHANNELS=8
        export LDCHANNELS=$ld
        echo "export LDCHANNELS=$ld" >> /tmp/cmdline
        if licenabled 45 ; then
            ld=$(licinfo -M 45 -t int -n MaxLines)
            export LOMCHANNELS=$ld
        else
            export LOMCHANNELS=0
        fi
        echo "export LOMCHANNELS=$ld" >> /tmp/cmdline



    fi # S2m / S0 Box

    SerialCode=$(licinfo -t string -n SerialCode)
    export SerialCode
    echo "export SerialCode=${SerialCode}" >> /tmp/cmdline
}

firstconfig () {

    if [ ! -e /data/config.lua ] ; then
        if which licinfo >/dev/null 2>&1; then
            xproductcode=$(licinfo -t int -n ProductCode)
            if [ -z "${xproductcode}" ] ; then
                # Missing or corrupt license
                let productcode=0
            else
                let productcode=$(licinfo -t int -n ProductCode)
            fi
        else
            # licinfo missing
            let productcode=0
        fi

        if [ $productcode -eq 101 ] ; then
            cfgfile="/usr/fb/OMG3-S2MFalc6.lua"
        elif [ $productcode -eq 102 ] ; then
            cfgfile="/usr/fb/OMG6-S2MFalc6.lua"
        elif [ $productcode -eq 103 ] ; then
            cfgfile="/usr/fb/OMGU3-S2MFalc6.lua"
        elif [ $productcode -eq 104 ] ; then
            cfgfile="/usr/fb/OMGU6-S2MFalc6.lua"
        elif [ $productcode -eq 105 ] ; then
            cfgfile="/usr/fb/SingleUnit1S0.lua"
        elif [ $productcode -eq 106 ] ; then
            cfgfile="/usr/fb/SingleUnit4S0.lua"
        elif [ $productcode -eq 107 ] ; then
            cfgfile="/usr/fb/OMG6-S2MFalc6.lua"
        elif [ $productcode -eq 108 ] ; then
            cfgfile="/usr/fb/OMG6-S2MFalc6.lua"
        elif [ $productcode -eq 109 ] ; then
            cfgfile="/usr/fb/MGB8.lua"
        elif [ $productcode -eq 110 ] ; then
            cfgfile="/usr/fb/MGB30.lua"
        elif [ $productcode -eq 111 ] ; then
            cfgfile="/usr/fb/MGB60.lua"
        elif [ $productcode -eq 114 ] ; then
            cfgfile="/usr/fb/MGB60+8+A.lua"

        else
            if [ "$HWTYPE" = "PCM" ]; then
                cfgfile="/usr/fb/PCM.lua"
            else
                touser "Unknown ProductCode: ${ProductCode}"
                if [ "${S2MID}" = "4" -o "${S2MID}" = "6" ] ; then
                    cfgfile="/usr/fb/OMG6-S2MFalc6.lua"
                else
                    cfgfile="/usr/fb/SingleUnit4S0.lua"
                fi
            fi
        fi

        if [ -e ${cfgfile} ] ; then
            cp ${cfgfile} /data/config.lua
        else
            echo "Missing file ${cfgfile}"
        fi
    fi
}


getval () {
    grep "string_${1}" /data/config.lua|sed -e 's/.*= "\(.*\)".*$/\1/' -e 's/\\//g'
}


prepareOmg() {
#prepare stuff on first start
    if [ ! -e /etc/omgFirstInitDone ] ; then
	rm /etc/hostname
    fi

#   O.K. let's go
    hostnamepar=""

    # Disable Console blanking
    setterm -powersave off -powerdown 0 -blank 0 >/dev/console 2>/dev/null
    # Let'splay it safe
    setterm -powersave off -powerdown 0 -blank 0 >/dev/tty1 2>/dev/null

    echo "# parameters stored in eeprom" >> /tmp/cmdline
    for i in $(</data/eeprom) ; do
	export $i
	echo "export $i" >> /tmp/cmdline ;
    done

# create needed dirs
    if [ ! -d /data ] ; then
	touserWarn "Creating /data"
	mkdir /data
    fi

# detect CPU
    CPU=$(grep -m 1 'model name.*:' </proc/cpuinfo| sed -e 's/Intel(R)//'|sed -e 's/  / /g'|cut -d ' ' -f 3|cut -d '(' -f 1)
    CPUs=$(grep -c 'model name.*:' </proc/cpuinfo)
    export CPU=$CPU
    export CPUs=$CPUs
    echo "# parameters from cpuinfo" >> /tmp/cmdline
    echo "export CPU=$CPU" >> /tmp/cmdline
    echo "export CPUs=$CPUs" >> /tmp/cmdline

# dump kernel cmdline to /tmp/cmdline
    touserOk "OMG: Get kernel commandline"
    echo "# parameters of the kernel commandline" >> /tmp/cmdline
    for i in $(</proc/cmdline) ; do
	if  echo $i|cut -d "=" -f 1| grep -q "[^A-Za-z0-9_]" ; then
        # parameter contains some illegal character for a bash variable
            continue
	else
            export $i
            echo "export $i" >> /tmp/cmdline ;
	fi
    done

# save mem on Geode
    if [ "$CPU" = "Geode" ] ; then
    # We don't need this
	if mount | grep -q '^lrm'; then
            umount lrm
	fi
    fi

# maybe detect architecture
    MACHINE="i386"
    export MACHINE=$MACHINE
    echo "export MACHINE=$MACHINE" >> /tmp/cmdline
    touserOk "OMG: Running on a $MACHINE"

    echo "# parameters from setup" >> /tmp/cmdline

    touserOk "OMG: find number of  channels"

# prepare i2c
    . /usr/bin/i2csetup
    echo "export I2CBUS=\"${I2CBUS}\"" >> /tmp/cmdline
    echo "export I2CCONFIGBUS=\"${I2CCONFIGBUS}\"" >> /tmp/cmdline
    echo "export I2CCONFIGADDRESS=${I2CCONFIGADDRESS}" >> /tmp/cmdline
    echo "export ILIDBUS=\"${ILIDBUS}\"" >> /tmp/cmdline

# detect hwtype
    hwtype="0000"

    if i2crdbox > /dev/null ; then
	hwtype=$(i2crdbox)
    fi
    if i2crdhwid > /dev/null ; then
	hwid=$(i2crdhwid)
    fi

    if [ -z "${hwtype}" ]; then
	hwtype="0000"
    fi

    if [ "${hwtype}" != "0000" -a "${CPU}" != "QEMU" ] ; then
    # Get serial
	sernum=$(i2crdserial | cut -d ' ' -f 1)
	rc=$?
	if [ ${rc} -eq 2 ]; then
            # Oups
            touserFail "OMG: Fatal error. Getting serial number failed, setting default"
            export sn=${sn}
	fi
	if [ "${sernum}" == "" ]; then
            sernum=$(i2crdhwserial | cut -d ' ' -f 1)
            rc=$?
            if [ ${rc} -eq 2 ]; then
                # Oups
		touserFail "OMG: Fatal error. Getting serial number failed, setting default"
		export sn=${sn}
            fi
	fi

	if [ "${sernum}" == "" ]; then
            # Mmh, Hamlet
            touserFail "No serial in eeprom found"
            export sn=${sn}
	fi

	if [ ${rc} -eq 1 ]; then
            touserFail "No serial in eeprom found, setting default"
            export sn=${sn}
	else
            export sn=${sernum}
	fi

	if ! grep -q "export sn=" /tmp/cmdline; then
            echo "export sn=\"${sn}\"" >> /tmp/cmdline
	fi

    # For Configurator
	export HWTYPE=''

	S0ID="unknown"
	S2MID="unknown"

	pciid=$(lspci -n | grep "1011:f" | sed -e "s/.*1011:\(....\).*/\\1/")

	if [ "${hwid}" = "01" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="QUADE1"
            export S2MSERNUM="$(i2crdhwserial)"
            subtype=$(i2crdsubtype)
            if [ "${subtype}" = "80" ] ; then
		export OEM=1
            else
		export OEM=0
            fi

            if [ "${subtype}" = "02" ] ; then
		export S2MID="6"
		chklicense
            else
		export S2MID="4"
            fi
	elif [ "${hwid}" = "02" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="AtomBox"
            export S2MSERNUM="$(i2crdhwserial)"
            echo "led 0 1830000" | /usr/bin/confTool /dev/ilid 0.a/X >/dev/null 2>&1
            subtype=$(i2crdsubtype)
            if [ "${subtype}" = "80" ] ; then
		export OEM=1
            else
		export OEM=0
            fi

            if [ "${subtype}" = "02" ] ; then
		export S2MID="6"
		chklicense
            else
		export S2MID="4"
            fi
	elif [ "${hwtype}" = "0100" ] ; then
            export HWFOUND=1
            export CHANNELS=2
            export CHIP="HFC4S"
            export HWTYPE="SingleUnit1S0"
            export OEM=0
            export S0ID=1
	elif [ "${hwtype}" = "0101" ] ; then
            export HWFOUND=1
            export CHANNELS=8
            export CHIP="HFC4S"
            export HWTYPE="SingleUnit4S0"
            export OEM=0
            export S0ID=1
	elif [ "${hwtype}" = "0102" ] ; then
            export HWFOUND=1
            export CHANNELS=8
            export CHIP="HFC4S"
            export HWTYPE="SingleUnit4S0"
            export OEM=0
            export S0ID=2
            chklicense

	elif [ "${hwtype}" = "0200" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="S2MPCIE"
            export OEM=0
            export S2MID="4"
            export S2MSERNUM="$(i2crdhwserial)"
	elif [ "${hwtype}" = "0201" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=1
            export HWTYPE="S2MPCIE"
            export OEM=0
            export S2MID="4"
            export S2MSERNUM="$(i2crdhwserial)"
	elif [ "${hwtype}" = "0202" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="S2MPCIE"
            export OEM=0
            export S2MID="6"
            export S2MSERNUM="$(i2crdhwserial)"
            chklicense
	elif [ "${hwtype}" = "0203" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHANNELS=60
            export CHIP="TDM"
            export RELAIS=1
            export HWTYPE="S2MPCIE"
            export OEM=0
            export S2MID="6"
            export S2MSERNUM="$(i2crdhwserial)"
            chklicense
	elif [ "${hwtype}" = "0280" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="S2MPCIE"
            export OEM=1
            export S2MID="4"
            export S2MSERNUM="$(i2crdhwserial)"

	elif [ "${hwtype}" = "0300" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="MGB"
            export OEM=0
            export S2MID="4"
            export S2MSERNUM="$(i2crdhwserial)"
	elif [ "${hwtype}" = "0302" -o "${hwtype}" = "0400" ] ; then
	    #in centos there is no 0x6f eeprom
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="MGB"
            export OEM=0
            export S2MID="6"
            export S2MSERNUM="$(i2crdhwserial)"
            chklicense
	elif [ "${hwtype}" = "0380" ] ; then
            export HWFOUND=1
            export CHANNELS=$(i2ccalclines)
            export CHIP="TDM"
            export RELAIS=0
            export HWTYPE="MGB"
            export OEM=1
            export S2MID="6"
            export S2MSERNUM="$(i2crdhwserial)"
	else
            touserWarn "OMG: Unknown hwtype"
	fi

	echo "export CHIP=${CHIP}" >> /tmp/cmdline
	echo "export HWTYPE=${HWTYPE}" >> /tmp/cmdline
	echo "export OEM=${OEM}" >> /tmp/cmdline
	echo "export HWFOUND=${HWFOUND}" >> /tmp/cmdline
	if [ "${S2MSERNUM}" != "unknown" ] ; then
            echo "export S2MSERNUM=\"${S2MSERNUM}\"" >> /tmp/cmdline
	fi
	if [ "${S0ID}" != "unknown" ] ; then
            echo "export S0ID=${S0ID}" >> /tmp/cmdline
	fi
	if [ "${S2MID}" != "unknown" ] ; then
            echo "export S2MID=${S2MID}" >> /tmp/cmdline
	fi

#touser "OMG: channels=$CHANNELS"

    else
        touserInfo "OMG: System without hardware just loop devices"
        export HWFOUND=1
        export HWTYPE="PCM"
        export CHANNELS=60
        export CHIP="NONE"

        getVMSernum

        export BOWL=1
        echo "export BOWL=1" >> /tmp/cmdline

        echo "export sn=\"${sn}\"" >> /tmp/cmdline
        echo "export CHIP=${CHIP}" >> /tmp/cmdline
        echo "export HWTYPE=${HWTYPE}" >> /tmp/cmdline
        echo "export OEM=${OEM}" >> /tmp/cmdline
        echo "export HWFOUND=${HWFOUND}" >> /tmp/cmdline
        echo "export CHANNELS=${CHANNELS}" >> /tmp/cmdline

        if licinfo -d > /dev/null ; then
            SerialCode=$(licinfo -t string -n SerialCode)
            export SerialCode
            echo "export SerialCode=${SerialCode}" >> /tmp/cmdline

            let ld=0
            if  licenabled 43 ; then
                ld=$(($ld+$(licinfo -M 43 -t int -n MaxLines)))
            fi
            if  licenabled 44 ; then
                ld=$(($ld+$(licinfo -M 44 -t int -n MaxLines)))
            fi
            if  licenabled 47 ; then
                ld=$(($ld+$(licinfo -M 47 -t int -n MaxLines)))
            fi
            if  licenabled 55 ; then
                ld=$(($ld+$(licinfo -M 55 -t int -n MaxLines)))
            fi

            echo "export LDCHANNELS=${LDCHANNELS}" >> /tmp/cmdline


            if licenabled 45 ; then
                ld=$(licinfo -M 45 -t int -n MaxLines)
                export LOMCHANNELS=${ld}
            else
                export LOMCHANNELS=0
            fi
            echo "export LOMCHANNELS=${LOMCHANNELS}" >> /tmp/cmdline
	fi
    fi # New box / old box / PCM


# Let's see whether this is the first boot

    if [ -x /usr/fb/firstrun ]; then
	touserInfo "OMG: First run"
	logger -t OMG "First run"

	/usr/fb/firstrun
	if [ $? -eq 0 ] ; then
	    rm -f /usr/fb/firstrun
	    firstdone=1
	else
	    touserFail "OMG: firstrun failed, take a look"
	fi
    fi

# Make sure that we have a config.lua
    firstconfig

#
# check Box mode
#

    BOXTYPE="classic"
    if test -f /data/config.lua ; then
	if grep -q 'bool_GatewayMode *= *true' /data/config.lua; then
	    BOXTYPE="gate"
	else
            BOXTYPE="classic"
	fi
    else
	touserWarn "OMG: Warning: cannot get boxtype from config"
    fi
    export BOXTYPE=$BOXTYPE
    echo "export BOXTYPE=$BOXTYPE" >> /tmp/cmdline


    if [ -z "${SerialCode}" ] ; then

	if ! grep -q "export sn=" /tmp/cmdline; then
            echo "export sn=\"${sn}\"" >> /tmp/cmdline
	fi

    # We have no license. Let's build a hostname

    # Try to get name from i2c
	if [ "x${OEM}" = "x1" ]; then
            hostname ${hostnamepar} "ONS${CHANNELS%0}$(padzeros $sn)"
	else
            i2chost="$(i2cinfo -l| head -n 1 | cut -d ':' -f 1| cut -d ',' -f 10)"
            if [ "x${i2chost}" == "x" ]; then
            # No hostname from i2c so let's do te oldfashioned way
		if [ "x${SYSTEM}" != "x" ] ; then
                    hostname ${hostnamepar} "${SYSTEM}"
		elif [ "x${HWTYPE}" = "xMGB" ] ; then
                    hostname ${hostnamepar} "OMSx$(padzeros $sn)"
		elif [ "x${HWTYPE}" = "xAtomBox" ] ; then
                    hostname ${hostnamepar} "OMG04$(padzeros $sn)"
		else
                    hostname ${hostnamepar} "OMG${CHANNELS%0}$(padzeros $sn)"
		fi
            elif [ "${i2chost}" != "unknown" ]; then
		hostname ${hostnamepar} "${i2chost}$(padzeros ${sn})"
            else
            # No hostname from i2c so let's do te oldfashioned way
		if [ "x${HWTYPE}" = "xMGB" ] ; then
                    hostname ${hostnamepar} "OMSx$(padzeros $sn)"
		elif [ "x${HWTYPE}" = "xAtomBox" ] ; then
                    hostname ${hostnamepar} "OMG04$(padzeros $sn)"
		else
                    hostname ${hostnamepar} "OMG${CHANNELS%0}$(padzeros $sn)"
		fi
            fi
            export SYSTEM=$(hostname)
	fi
    else
    # We have license
	hostname ${hostnamepar} "${SerialCode%%,*}" # In case of license is adding names ...

	if [ "x${SYSTEM}" != "x" ] ; then
            export SYSTEM=${SerialCode%%,*}
	else
            export SYSTEM=${SerialCode%%,*}
	fi
    fi

    # Perhaps hostname defined by user
    if [ -e /data/hostname ] ; then
	hn=$(cat /data/hostname)
	hostname ${hostnamepar} ${hn}
	echo "export HOSTNAME=${hn}" >>/tmp/cmdline
    fi

    echo $(/bin/hostname) >/etc/hostname
    touserInfo "OMG: hostname $(hostname)"

    sed -i -e "s#HOSTNAME=.*#HOSTNAME=$(hostname)#" /etc/sysconfig/network 

    echo "# environment for all users/programs" >> /tmp/cmdline
    echo "export SYSTEM=${SYSTEM}" >> /tmp/cmdline
    echo "export CHANNELS=$CHANNELS" >> /tmp/cmdline
#

    # Prepare rsyslog
    if [ -L /etc/rsyslog.d ];then
	if [ -e /tmp/rsyslog.d ];then
            mkdir -p /tmp/rsyslog.d
	fi
    fi

    if [ ! -d /var/spool/rsyslog ]; then
	mkdir -p /var/spool/rsyslog 2>/dev/null
    fi

    chmod 777 /var/log

    # No logging defs in rsyslog.conf
    sed -i -e '/#### RULES ####/,/### begin forwarding rule ###/{//!d}' /etc/rsyslog.conf
    # Set rsyslog's rate limit
    
    RATELIMITINTERVAL=0  # Disable rate limit
    RATELIMITBURST=0
    IMUXSOCKETRATE=0

    sed -n "/^\$SystemLogRateLimitInterval/ q 99" /etc/rsyslog.conf
    if [ $? -eq 99 ]; then
	sed -i -e "/^\$SystemLogRateLimitInterval/c\$SystemLogRateLimitInterval ${RATELIMITINTERVAL}" /etc/rsyslog.conf
    else
	sed -i -e "/^\$ModLoad imuxsock/a\$SystemLogRateLimitInterval ${RATELIMITINTERVAL}" /etc/rsyslog.conf
    fi
    sed -n "/^\$SystemLogRateLimitBurst / q 99" /etc/rsyslog.conf
    if [ $? -eq 99 ]; then
	sed -i -e "/^\$SystemLogRateLimitBurst/c\$SystemLogRateLimitBurst ${RATELIMITBURST}" /etc/rsyslog.conf
    else
	sed -i -e "/^\$ModLoad imuxsock/a\$SystemLogRateLimitBurst ${RATELIMITBURST}" /etc/rsyslog.conf
    fi
    sed -n "/^\$IMUXSockRateLimitInterval / q 99" /etc/rsyslog.conf
    if [ $? -eq 99 ]; then
	sed -i -e "/^\$IMUXSockRateLimitInterval/c\$IMUXSockRateLimitInterval ${IMUXSOCKETRATE}" /etc/rsyslog.conf
    else
	sed -i -e "/^\$ModLoad imuxsock/a\$IMUXSockRateLimitInterval ${IMUXSOCKETRATE}" /etc/rsyslog.conf
    fi

    # Disable throttling                                                                           
    if ! grep -q "\$ActionQueueTimeoutEnqueue 0" /etc/rsyslog.conf; then
	line=$(sed -ne '/^#### GLOBAL DIRECTIVES ####$/=' /etc/rsyslog.conf)
	if [ "$line" = "" ]; then
            echo "I'm goofed  GLOBAL DIRECTIVES not found, adding at top"
            sed -ie "1i\$ActionQueueTimeoutEnqueue 0" /etc/rsyslog.conf
	else
            let line=$line+1
            sed -ie "${line}a\$ActionQueueTimeoutEnqueue 0" /etc/rsyslog.conf
	fi
    fi
    
    /usr/bin/switchsyslog

# Get Proxy for apt
    if [ ! -z "${HTTP_PROXY}" ] ; then
	echo "Setting apt-get proxy to ${HTTP_PROXY}"
	echo "export HTTP_PROXY=${HTTP_PROXY}" >> /tmp/cmdline
    fi

# Get package version numbers
# Get package version numbers
    VUSER=$(omgversion  --filter='omg.version' --val)
    VMODULES=$(omgversion  --filter='omg.modules.version' --val)
    echo "export VUSER=${VUSER}" >> /tmp/cmdline
    echo "export VMODULES=${VMODULES}" >> /tmp/cmdline

# Disable reverse DNS in sshd
    sed -i -e '/UseDNS/d' /etc/ssh/sshd_config
    echo "UseDNS no" >> /etc/ssh/sshd_config

    if [ -e /etc/default/snmpd ]; then
	sed -i -e '/SNMPDOPTS/c SNMPDOPTS="-m all -LS3d -Lf /dev/null -u snmp -I -smux -p /var/run/snmpd.pid -x /tmp/agentx udp:161 udp6:161"' /etc/default/snmpd
    fi

# set time staff
    if which settimezone >/dev/null 2>&1; then
	TZ=$(getval TimeZone)
	settimezone ${TZ}
    fi
    
    if [ -z "${NTPSERVER}" ] ; then
	NTPSERVER=$(getval NtpServer)
    fi
    
    if [ ! -z "${NTPSERVER}" ]; then
	if grep -q "^export NTPSERVER=" /tmp/cmdline;then
            sed -i -e "/^export NTPSERVER=/cexport NTPSERVER=\"${NTPSERVER}\"" /tmp/cmdline
	else
	    echo "export NTPSERVER=${NTPSERVER}" >> /tmp/cmdline
	fi

	if [ -e /etc/ntp.conf ]; then
            sed -i -e '/^server.*added by \/sbin\/dhclient-script/d' -e "/^server/cserver ${NTPSERVER}" /etc/ntp.conf
	else
            echo "server ${NTPSERVER}" > /etc/ntp.conf
	fi
	
    fi
    
# Setup SNMP

# get values from config.lua
    SNMPLOCATION=$(getval SnmpLocation)
    SNMPCONTACT=$(getval SnmpContact)
    SNMPROC=$(getval SnmpRoc)
    SNMPRWC=$(getval SnmpRwc)
    SNMPTRAPSINK=$(getval SnmpTrapsink)

    if [ -z "${SNMPROC}" ] ; then
	SNMPROC="public"
    fi

    if [ -z "${SNMPRWC}" ] ; then
        SNMPRWC="Seife.ist.selten.schmackhaft"
    fi
    
    if [ -z "${SNMPLOCATION}" ] ; then
	SNMPLOCATION="OfficeMasterGate"
    fi
    
    if [ -z "${SNMPCONTACT}" ] ; then
	SNMPCONTACT="OMG Admin"
    fi
    
    if [ -z "${SNMPTRAPSINK}" ] ; then
	SNMPTRAPSINK=127.0.0.1
    fi

    
    if test -e /etc/snmp/snmpd.conf && grep -q '^#LOCKED$' /etc/snmp/snmpd.conf; then
        echo "OMG: /etc/snmp/snmpd.conf is intentionally locked"
        # omgsnmp needs these
        SNMPROC=$(sed -n -e '/rocommunity /s/^rocommunity //p' /etc/snmp/snmpd.conf)
        SNMPRWC=$(sed -n -e '/rwcommunity /s/^rwcommunity //p' /etc/snmp/snmpd.conf)
        SNMPLOCATION=$(sed -n -e '/syslocation /s/^syslocation //p' /etc/snmp/snmpd.conf)
        SNMPCONTACT=$(sed -n -e '/syscontact /s/^syscontact //p' /etc/snmp/snmpd.conf)
        SNMPTRAPSINK=$(sed -n -e '/trapsink /s/^trapsink //p' /etc/snmp/snmpd.conf)
    else
        mkdir -p /etc/snmp
        cat >/etc/snmp/snmpd.conf <<EOF
# Generated by omg
master agentx
iquerySecName _internal
EOF
        test ! -z "${SNMPRWC}"  && echo "rwcommunity ${SNMPRWC}" >>/etc/snmp/snmpd.conf
        test ! -z "${SNMPRWC}"  && echo "rwcommunity6 ${SNMPRWC}" >>/etc/snmp/snmpd.conf
        test ! -z "${SNMPROC}"  && echo "rocommunity ${SNMPROC}" >>/etc/snmp/snmpd.conf
        test ! -z "${SNMPROC}"  && echo "rocommunity6 ${SNMPROC}" >>/etc/snmp/snmpd.conf
        test ! -z "${SNMPCONTACT}"  && echo "syscontact ${SNMPCONTACT}" >>/etc/snmp/snmpd.conf
        test ! -z "${SNMPLOCATION}" && echo "syslocation ${SNMPLOCATION}" >>/etc/snmp/snmpd.conf
        if [ ! -z "${SNMPTRAPSINK}" ]; then
            for i in ${SNMPTRAPSINK};do
                echo "trapsink ${i}" >>/etc/snmp/snmpd.conf
                echo "trap2sink ${i}" >>/etc/snmp/snmpd.conf
            done
        fi
        
        # if hp-health is installed we need this 
        producer=$(dmidecode -s system-manufacturer)
        if [  "${producer}" = "HP" -a -e /usr/lib/libcmaX.so ]; then
            echo "dlmod cmaX /usr/lib/libcmaX.so" >>/etc/snmp/snmpd.conf
        fi
        

    fi
    if grep -q "^export SNMPROC=" /tmp/cmdline;then
        sed -i -e "/^export SNMPROC=/cexport SNMPROC=\"${SNMPROC}\"" /tmp/cmdline
    else
        echo "export SNMPROC=\"${SNMPROC}\"" >> /tmp/cmdline
    fi
    
    if grep -q "^export SNMPRWC=" /tmp/cmdline;then
        sed -i -e "/^export SNMPRWC=/cexport SNMPRWC=\"${SNMPRWC}\"" /tmp/cmdline
    else
        echo "export SNMPRWC=\"${SNMPRWC}\"" >> /tmp/cmdline
    fi
    if grep -q "^export SNMPLOCATION=" /tmp/cmdline;then
        sed -i -e "/^export SNMPLOCATION=/cexport SNMPLOCATION=\"${SNMPLOCATION}\"" /tmp/cmdline
    else
        echo "export SNMPLOCATION=\"${SNMPLOCATION}\"" >> /tmp/cmdline
    fi
    
    if grep -q "^export SNMPCONTACT=" /tmp/cmdline;then
        sed -i -e "/^export SNMPCONTACT=/cexport SNMPCONTACT=\"${SNMPCONTACT}\"" /tmp/cmdline
    else
        echo "export SNMPCONTACT=\"${SNMPCONTACT}\"" >> /tmp/cmdline
    fi
    if grep -q "^export SNMPTRAPSINK=" /tmp/cmdline;then
        sed -i -e "/^export SNMPTRAPSINK=/cexport SNMPTRAPSINK=\"${SNMPTRAPSINK}\"" /tmp/cmdline
    else
        echo "export SNMPTRAPSINK=\"${SNMPTRAPSINK}\"" >> /tmp/cmdline
    fi
    service snmpd restart
    
#trigger_watchdog 2>/dev/null >/dev/null &

# updconfd seems to have some problems on SBA when eeprom is missing
    if [ ! -e /data/eeprom ] ; then
	if [ -e /usr/fb/eeprom.empty ] ; then
	    cp /usr/fb/eeprom.empty /data/eeprom
	fi
    fi

    if [ -e /data/configpatch ] ; then
	/data/configpatch
    fi


    board=$(dmidecode -s baseboard-product-name| sed -e 's/ //g')
    if [ -z "${board}" ]; then
	if which cgutlcmd >/dev/null 2>&1;then
            if cgutlcmd cginfo /ot:board /dump /cgos 2>/dev/null >/dev/null ;then
		board="cgt"
            fi
	fi
    fi
    
    rootdev=''

# Better: replace if exist
    if [ -e /usr/bin/fpgaversion ] ; then
	FPGAVERSION=$(/usr/bin/fpgaversion | head -n 1 | cut -d ' ' -f 4)
	echo "export FPGAVERSION=${FPGAVERSION}" >>/tmp/cmdline
    fi

# Perhaps is left over from GateConfig
    rm -f /var/config.active

    echo "$0 stop: $(date)" >> /tmp/sequence
}

startOmg() {
    echo "$0 start: $(date)" >> /tmp/sequence

#
# some functions
#
    export TERM=linux

    . /tmp/cmdline

#check /data
    if [ -e /usr/bin/omgcheckdisk ] ; then
         /usr/bin/omgcheckdisk
    fi

#get network info
    /usr/bin/omgnetworkchanged
    echo $sn >/data/serial.txt
#prepare stuff on first start
    if [ ! -e /etc/omgFirstInitDone ] ; then
	/usr/bin/omgsetnetwork
	service rsyslog stop
	rm /var/log/messages
	/usr/bin/switchsyslog
	service rsyslog start
	touch /etc/omgFirstInitDone
	reboot
    fi

# start reset daemon
    touserOk "OMG: Start factory reset daemon"
    if [ $(ps ax| grep parport|grep -v grep| wc -l) -gt 0 ]; then
   # parport ist already running
	killall parport 2>/dev/null
    fi
    parport 2>&1 | logger -t parport -p local5.notice &

# start snfsserver 
    touserOk "OMG: Start snfsserver"
    killall snfsserver 2>/dev/null
    snfsserver 0.0.0.0 3215 2>&1 | logger -t snfsserver -p local5.notice &

#start udpconfd as soon as possible
    touserOk "OMG: Start udpconfd"
    killall udpconfd 2>/dev/null
    udpconfd 2>&1 | logger -t udpconfd -p local5.notice &

#start omgsnmp
    touserOk "OMG: Start omgsnmp"
    killall omgsnmp 2>/dev/null
    omgsnmp

# Lets start Watchdog process via checkntp
    WDHOLE=1
    export WDHOLE
    echo "export WDHOLE=${WDHOLE}" >> /tmp/cmdline
    checkntp -s

# Start GSM modem
    which omgsmssetup >/dev/null 2>&1 && omgsmssetup start

# Start the mess

    if which omgstart >/dev/null 2>&1; then
	touserOk "OMG: Start omgstart"
	omgstart rc 2>&1 | logger -t omgstart -p local5.notice &

    else 
	touserFail "OMG:   User fs not found, start system upgrade!"
    fi

    initctl --quiet start omgmenu 2>/dev/null >/dev/null

    echo "$0 stop: $(date)" >> /tmp/sequence
}


start ()
{
    prepareOmg
    omgstartilid
    startOmg
    touch $lockfile
}

stop () {
    omgstop
    rm -f $lockfile
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    status)
	status $prog
	;;
    restart|force-reload)
	stop
	start
	;;
    try-restart|condrestart)
	if status $prog > /dev/null; then
	    stop
	    start
	fi
	;;
    reload)
	exit 3
	;;
    *)
	echo $"Usage: $0 {start|stop|status|restart|try-restart|force-reload}"
	exit 2
esac
