#!/bin/sh

. /lib/functions.sh
. /usr/lib/configsync_lib.sh

my_logger() {
   logger -t configsync_handler "${@}"
}

create_local_configuration_file() {
#if it it not feasable that the uuid changes every  time the service is started make the uuid persistent
        UUID=$(cat /proc/sys/kernel/random/uuid)
        if [ "$(uci_get ${MY_SERVICE_NAME} global configured)" = 1 ]; then
            CONFIGURED="yes"
        else
            CONFIGURED="no"
        fi

        cat > ${CONFIGSYNC_CONFIGURATION_FILE}<<EOF
[interfaces]
i0=br-lan,B
[network]
interface=br-lan
almac=${ETH_MAC_ADDR}
unicasttobridge=on
[wsc]
authenticationtypes=Open,WPAPersonal,WPA2Personal
encryptiontypes=None,AES
connectiontypes=ESS
configurationmethods=VirtualPB
primarydevicetype=NetworkInfrastructure,Bridge
osversion=1
devicepasswordid=UserSpecified
manufacturer=$(eval "$(grep DEVICE_MANUFACTURER= /etc/device_info)"; echo $DEVICE_MANUFACTURER)
modelname=$(uci_get delos delos device_type)
devicename=$(eval "$(grep DEVICE_PRODUCT= /etc/device_info)"; echo $DEVICE_PRODUCT)
modelnumber=9999
serialnumber=$(uci_get_state delos baptization SerialNumber)
uuide=${UUID}
[wscregistrar]
freqband=CS
ssid=devolo-WiFi-Passwd
networkkey=devolo-WiFi
authenticationtype=WPA2Personal
encryptiontype=AES
[configuration]
registrar=off
renewonstart=on
autoconfigsearchtimer=30
[configsync]
enabled=yes
version=1
configured=${CONFIGURED}
useplcbutton=off
priority=0
domain=$(uci_get ${MY_SERVICE_NAME} global domain 0)
logging=$(uci_get ${MY_SERVICE_NAME} global logging 0)
[orange]
orangetlv=off
orangetlvm2=off
orangeexpbackoff=off
orangeconstbackoff=0
[debug]
encryption=on
messageidcheck=on
EOF
}

handle_event()
{
    MESSAGE_TYPE=${1}
    MESSAGE=${2}
    EVENT=${3}

    my_logger "handle_event: ${MESSAGE_TYPE} '${MESSAGE}', event ${EVENT}"

    # copy configuration to temp configuration
    wait_stable_config 0 5
    [ "$event" = configsync_to_system ] &&
        rm -rf $CS_TEMP_CONFIG_PATH/* $CS_TEMP_CHANGE_PATH/*
    for CONFIGFILE in ${CS_SERVICES_TO_SYNC}; do
	# ATT! this export will also export uncommitted changes!
        uci -q export $CONFIGFILE | uci_tmp import $CS_PREFIX$CONFIGFILE
    done

    RETVAL=1
    for CHANGE in ${MESSAGE}; do
        EXECUTOR=${CHANGE}
        my_logger  "Got event ${EVENT} for change ${CHANGE}, calling ${EXECUTOR}"
        if [ -f ${PATH_TO_CONFIGSYNC_EXECUTOR}/${EXECUTOR} ]; then
            if ${PATH_TO_CONFIGSYNC_EXECUTOR}/${EXECUTOR} ${EVENT} ${CHANGE}; then
                RETVAL=0
            fi
        else
            if [ "${CHANGE}" != "${MESSAGE_TYPE}" ]; then
                my_logger  "Can not handle change ${CHANGE}!"
            fi
        fi
    done

    # check for changed configfiles and import to system configuration
    if [ -s $CS_IMPORTSERVICELIST ]; then
        # wait until configfiles are not in use
        wait_stable_config 0 5
        IMPORTSERVICELIST=$(cat $CS_IMPORTSERVICELIST)
        for CONFIGFILE in ${IMPORTSERVICELIST}; do
            uci revert ${CONFIGFILE}
            uci_tmp export ${CS_PREFIX}${CONFIGFILE} | uci import ${CONFIGFILE}
            update_md5sum ${CONFIGFILE}
        done
        >$CS_IMPORTSERVICELIST
    fi
    return $RETVAL
}

start_p1905()
{
    my_logger ">>> start_p1905()"

    # wait on first start after device boot
    STARTDELAY=$(uci_get ${MY_SERVICE_NAME} global startdelay 0)
    EXTENSIONDELAY=$(uci_get ${MY_SERVICE_NAME} global extensiondelay 20)
    wait_stable_config ${STARTDELAY} ${EXTENSIONDELAY}

    for SERVICE in ${CS_SERVICES_TO_SYNC}; do
        update_md5sum ${SERVICE}
    done

    rm -f /tmp/cs_omit_wireless
    killall p1905
    # call init() for all files (not directories!) in PATH_TO_CONFIGSYNC_EXECUTOR
    find ${PATH_TO_CONFIGSYNC_EXECUTOR} -type f -maxdepth 1 -exec sh -c "echo \"Call initialization of {} ...\"; {} init" \;

    create_local_configuration_file
    /usr/sbin/p1905 -f ${CONFIGSYNC_CONFIGURATION_FILE} | while read MESSAGE_TYPE MESSAGE
    do
        case ${MESSAGE_TYPE} in
            AUTOCONFIG-FAILED)
                my_logger  "Message ${MESSAGE_TYPE} ${MESSAGE} ignored"
                ;;
            NEW-AP-SETTINGS)
                my_logger  "Message ${MESSAGE_TYPE} ${MESSAGE} ignored"
                ;;
            CONFIGSYNC-SET-CONFIGURED)
                my_logger  "Message ${MESSAGE_TYPE} ${MESSAGE} setting configsync state to configured"
                uci_set configsync global configured '1'
                uci_commit configsync
                create_local_configuration_file
                ;;
            NEW-CONFIGSYNC-SETTINGS)
                # kill pending events from own website
                killall configsync_event_delay.sh
                >$CS_SERVICELIST
                handle_event ${MESSAGE_TYPE} "${MESSAGE}" configsync_to_system
                reload_config
                ;;
            CONFIGSYNC-DYNAMIC-UPDATE)
                handle_event ${MESSAGE_TYPE} "${MESSAGE}" dynamic_update
                ;;
            CONFIGSYNC-RESET)
                my_logger  "Message ${MESSAGE_TYPE} ${MESSAGE} received"
                rm $CS_CONFIGURATION_PATH/*
                find ${PATH_TO_CONFIGSYNC_EXECUTOR} -type f -maxdepth 1 -exec sh -c "echo \"Call initialization of {} ...\"; {} init" \;
                ;;
            VENDOR-MESSAGE)
                my_logger "Vendor message received"
                # cut off the VENDOR-MESSAGE prefix, decode base64 data and call service handler
                /usr/bin/configsync_vs_handler.sh $(echo "$MESSAGE" | cut -d' ' -f2 | openssl enc -base64 -d)
                ;;
        *)
                my_logger  "Unknown message ${MESSAGE_TYPE} ${MESSAGE}"
                ;;
        esac
    done
}

case ${1} in
    SYSTEM-TO-CONFIGSYNC)
        handle_event NEW-SYSTEM-CONFIG-SETTINGS "${2}" system_to_configsync
        ;;
    APPLY)
        my_logger  "APPLY) Apply configsync changes"
        killall -USR1 p1905
        ;;
    STOP)
        my_logger  "STOP) Stop p1905"
        killall p1905 2>/dev/null
        ;;
    START)
        ETH_MAC_ADDR=${2}
        my_logger  "START) Start p1905 with ${ETH_MAC_ADDR}"
        start_p1905
        ;;
esac