#!/bin/bash

### BEGIN INIT INFO
# Provides:          kgateway-firstboot
# Required-Start:    $local_fs +networking
# Required-Stop:     
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Start-Before:    khomp khompdrv klogserver kmpserver k3lserver kqueryserver kibs kgateway
# Short-Description: Khomp Gateway first boot configurations
### END INIT INFO

## configurable options
NETDEV=eth1
MAXTRY=20

## usefull paths, files and variables
MYNAME=`basename ${0}`
DEVICESYAML=/etc/khomp/config/devices.yaml
DEVICESYAMLTMP=/etc/khomp/config/devices.yaml.in
DEVICES=/etc/khomp/devices
SYSDEV=/sys/class/net/${NETDEV}
KONCHAKEY=/etc/khomp/key.konchasshd
## send forked processes std(out/err) to debug log
LOG=/var/log/debug

## binaries
CAT=/bin/cat
ECHO=/bin/echo
CP=/bin/cp
MV=/bin/mv
RM=/bin/rm
PIDOF=/bin/pidof
SLEEP=/bin/sleep
DATE=/bin/date
SED=/bin/sed
GREP=/bin/grep
INSSERV=/sbin/insserv
SYSCTL=/sbin/sysctl
TAIL=/usr/bin/tail
HEAD=/usr/bin/head
AWK=/usr/bin/mawk
CUT=/usr/bin/cut
SVC=/usr/sbin/service
KGW=/usr/sbin/kgwinstall
KSM=/usr/sbin/kswitch-mgmt
KWH=/usr/sbin/kwebhelper
KLOG=/usr/sbin/klog-shell

function log() {
    ${KLOG} -c -d "kgateway-firstboot" -f update.log -i GATEWAY -l ${1} -m "${2}"
}

[ -x ${KWH} ] || {
    log ERROR "kwebhelper not found"
    exit 1
}

function checkdevup() {
    [ -e ${SYSDEV} ] || {
        log ERROR "Network interface not found"
        return 1
    }
    T=0
    while [ "`${CAT} ${SYSDEV}/operstate`" != "up" ]; do
        [ ${T} -eq ${MAXTRY} ] && {
            log ERROR "Timeout waiting for network interface"
            return 1
        }
        log INFO "Waiting network interface to become available [${T}]"
        ${SLEEP} 1
        let T=T+1
    done
    return 0
}

function runkgwinstall() {
    [ -x ${KGW} ] || {
        log ERROR "kgwinstall not found"
        return 1
    }
    log INFO "Running kgwinstall"
    ${KGW} ${NETDEV} >> ${LOG} 2>&1 || {
        log ERROR "kgwinstall error: $?"
        return 1
    }
    return 0
}

function disableswitchports() {
    [ -x ${KSM} ] || {
        log ERROR "kswitch-mgmt not found"
        return 1
    }
    for P in 0 1 2; do
        log INFO "Disabling SWITCH port ${P}"
        ${KSM} set ${NETDEV} SMI_DEVPORT${P} SMI_PORTADDR_CTL0 0x007C > /dev/null 2>> ${LOG} || return $?
        ${KSM} set ${NETDEV} SMI_DEVPORT${P} SMI_PORTADDR_LEDCTL 0x80FF > /dev/null 2>> ${LOG} || return $?
        ${KSM} set ${NETDEV} SMI_DEVPORT${P} SMI_PORTADDR_LEDCTL 0x90FF > /dev/null 2>> ${LOG} || return $?
    done
    return 0
}

function enableswitchports() {
    [ -x ${KSM} ] || {
        log ERROR "kswitch-mgmt not found"
        return 1
    }
    for P in 0 1 2; do
        log INFO "Enabling SWITCH port ${P}"
        ${KSM} set ${NETDEV} SMI_DEVPORT${P} SMI_PORTADDR_CTL0 0x007F > /dev/null 2>> ${LOG} || return $?
        ${KSM} set ${NETDEV} SMI_DEVPORT${P} SMI_PORTADDR_LEDCTL 0x8033 > /dev/null 2>> ${LOG} || return $?
        ${KSM} set ${NETDEV} SMI_DEVPORT${P} SMI_PORTADDR_LEDCTL 0x9033 > /dev/null 2>> ${LOG} || return $?
    done
    return 0
}

function waitprocup() {
    PID=`${PIDOF} ${1} 2> /dev/null`
    T=0
    while [ $? -ne 0 ]; do
        [ ${T} -eq ${MAXTRY} ] && {
            log ERROR "Timeout waiting ${1} startup"
            return 1
        }
        log INFO "Waiting ${1} startup (${T})"
        ${SLEEP} 1
        let T=T+1
        PID=`${PIDOF} ${1} 2> /dev/null`
    done
    return 0
}

function startbasicservices() {
    [ -x ${SVC} ] || {
        log ERROR "service not found"
        return 1
    }
    [ -f ${DEVICES} ] && {
        rm -f ${DEVICES} || {
            log ERROR "Unable to remove file ${DEVICES}"
            return 1
        }
    }
    ${SVC} klogserver start >> ${LOG} 2>&1 || {
        log ERROR "Unable to start klogserver"
        return 1
    }
    waitprocup klogserver || return 1
    ${SVC} kibs start >> ${LOG} 2>&1 || {
        log ERROR "Unable to start kibs"
        return 1
    }
    waitprocup kibs || return 1
    return 0
}

function configureebs() {
    T=0
    while [ ! -e ${DEVICES} ]; do
        [ ${T} -eq ${MAXTRY} ] && {
            log ERROR "Timeout waiting EBS broadcast"
            return 1
        }
        log INFO "Waiting EBS broadcast (${T})"
        ${SLEEP} 2
        let T=T+1
    done
    DEV=`${HEAD} -1 ${DEVICES}`
    EBSSN=`${ECHO} ${DEV} | ${AWK} '{print $2}'`
    EBSMODEL=`${ECHO} ${DEV} | ${AWK} '{print $3}'`
    ## check if EBSMODEL has version
    EBSVERSION=`${ECHO} ${EBSMODEL} | ${CUT} -f1 -d"-"`
    ${ECHO} ${EBSVERSION} | ${GREP} "_V" > /dev/null
    [ $? -eq 0 ] && {
        ## grab EBSVERSION
        EBSVERSION=`${ECHO} ${EBSVERSION} | ${CUT} -f2 -d"_"`
        ## fix EBSMODEL
        EBSMODEL=`${ECHO} ${EBSMODEL} | ${SED} -r 's/_V[0-9]+//g'`
    } || {
        EBSVERSION="V1"
    }
    log INFO "Detected EBS ${EBSMODEL} with serial number ${EBSSN}"
    log INFO "Writing devices.yaml"
    ${CAT} > ${DEVICESYAMLTMP} 2>> ${LOG} << EOYAML
# Khomp configuration file
# Please note that indentation denotes scope but TABs are not permitted
# All fields are case sensitive
# Generated by: ${MYNAME}

---
Devices:
  -
    ${EBSSN}:
      Type: ${EBSMODEL}
      IP: 172.31.249.2
      Version: ${EBSVERSION}
      Links: []
EOYAML

    [ $? -ne 0 ] && {
        log ERROR "Unable to create devices.yaml"
        return 1
    }

    ${MV} -f ${DEVICESYAMLTMP} ${DEVICESYAML} 2>> ${LOG} || {
        log ERROR "Unable to rename devices.yaml temporary file"
        return 1
    }

    MYHOSTNAME="kmg${EBSSN}"
    log INFO "Setting hostname to ${MYHOSTNAME}"
    ${ECHO} ${MYHOSTNAME} > /etc/hostname 2>> ${LOG} || {
        log ERROR "Unable to write hostname file"
        return 1
    }
    ${SYSCTL} kernel.hostname=${MYHOSTNAME} >> ${LOG} 2>&1 || {
        log ERROR "Unable to set new hostname"
        return 1
    }
    return 0
}

function waitprocdown() {
    PID=`${PIDOF} ${1} 2> /dev/null`
    T=0
    while [ $? -ne 1 ]; do
        [ ${T} -eq ${MAXTRY} ] && {
            log ERROR "Timeout waiting ${1} [${PID}] shutdown"
            return 1
        }
        log INFO "Waiting ${1} [${PID}] shutdown (${T})"
        sleep 1
        let T=T+1
        PID=`${PIDOF} ${1} 2> /dev/null`
    done
    return 0
}

function stopbasicservices() {
    [ -x ${SVC} ] || {
        log ERROR "service not found"
        return 1
    }
    ${SVC} kibs stop >> ${LOG} 2>&1 || {
        log ERROR "Unable to stop kibs"
        return 1
    }
    waitprocdown kibs || return 1
    ${SVC} klogserver stop >> ${LOG} 2>&1 || {
        log ERROR "Unable to stop klogserver"
        return 1
    }
    waitprocdown klogserver || return 1
    return 0
}

function createkonchakeys() {
    [ -f ${KONCHAKEY} ] && {
        log INFO "Removing old shell keys"
        rm -f ${KONCHAKEY} >> ${LOG} 2>&1 || {
            log ERROR "Unable to remove private key"
            return 1
        }
        rm -f ${KONCHAKEY}.pub >> ${LOG} 2>&1 || {
            log ERROR "Unable to remove public key"
            return 1
        }
    }
    log INFO "Creating shell keys"
    ssh-keygen -q -b 1024 -t rsa -P "" -f /etc/khomp/key.konchasshd >> ${LOG} 2>&1 || {
        log ERROR "Unable to create shell keys"
        return 1
    }
    return 0
}

function removefromboot() {
    [ -x ${INSSERV} ] || {
        log ERROR "insserv not found"
        return 1
    }
    ${INSSERV} -r ${MYNAME} >> ${LOG} 2>&1 || {
        log ERROR "Unable to remove from boot"
        return 1
    }
    return 0
}

case "${1}" in
    start|force-start)
        log INFO "Starting gateway first boot configurations"
        checkdevup || exit $?
        runkgwinstall || exit $?
        [ "${1}" != "force-start" -a "`${KWH} config devices.yaml Devices | ${TAIL} -1`" != "[]" ] && {
            log INFO "devices.yaml has ben changed, ignoring EBS detection"
        } || {
            log INFO "Creating devices.yaml"
            disableswitchports || exit $?
            startbasicservices || exit $?
            configureebs || exit $?
            stopbasicservices || exit $?
            enableswitchports || exit $?
        }
        createkonchakeys || exit $?
        removefromboot || exit $?
    ;;
    stop|restart)
        log INFO "Dummy action: ${1}"
    ;;
    status)
        [ "`${KWH} config devices.yaml Devices | ${TAIL} -1`" = "[]" ] && ${ECHO} "not installed" || ${ECHO} "installed"
    ;;
    *)
        log ERROR "Unsupported action ${1}"
        ${ECHO} "Usage: ${MYNAME} {start|stop|restart|status|force-start}"
    ;;
esac

