#!/bin/sh

. /usr/bin/pcb_common.sh

name="cwmp-plugin"
start_options="-c /usr/lib/cwmp/cwmp_plugin.odl"
datamodel="ManagementServer"
trace_zones=""
component="sah_services_tr069"

PIDCWMP="/var/run/cwmpd.pid"
CWMP="cwmpd -vv -d /usr/lib/cwmp/libdmda_pcb.so"

CWMPDCERTS=/usr/lib/cwmp/cwmpdcerts.pem

CWMPDACACHE="/cfg/system//cwmp_acache.txt"

start()
{
    if [ -e /usr/lib/cwmp/cwmp_acache.txt ] && [ ! -e ${CWMPDACACHE} ]; then
         logger -t cwmp "Set cwmp parameters default attributes"
         cp /usr/lib/cwmp/cwmp_acache.txt ${CWMPDACACHE}
    fi

    if [ -e "/etc/config/cwmpd_upgrade_persistent.upd" ]; then
        echo "/etc/config/cwmpd_upgrade_persistent.upd exists:"
        cp /etc/config/cwmpd_upgrade_persistent.upd /tmp/cwmpd_upgrade_persistent.upd
        cat /etc/config/cwmpd_upgrade_persistent.upd
    fi

    if pcb_is_running $name; then
        echo "ManagementServer already started"
    else
        sahenv -f /etc/environment pcb_app -vv -n $name $start_options;
    fi

    if app_is_running cwmpd; then
        echo "cwmpd already started"
    else
        export SAH_TRACE_ZONES=DM_DA,DM_COM,DM_ENGINE,pcb_con
        if [ -e ${CWMPDCERTS} ]; then
            pcb_con=0 DM_DA=200 DM_COM=200 DM_ENGINE=200 ${CWMP} --trustedCA=${CWMPDCERTS};
        else
            pcb_con=0 DM_DA=200 DM_COM=200 DM_ENGINE=200 ${CWMP};
        fi
    fi
}

stop() {
    if app_is_running cwmpd; then
        kill $(cat ${PIDCWMP});
    else
        echo "cwmpd already stopped"
    fi

    pcb_stop $name
}

restart() {
    stop
    while app_is_running cwmpd; do
        sleep 1
    done
    while pcb_is_running $name; do
        sleep 1
    done
    start
}

backup() {
    if pcb_is_running $name; then
        pcb_cli "ManagementServer.export($2)"
    else
        echo "ManagementServer is not running, impossible to make a backup"
    fi
}

restore() {
    mkdir -p /var/lib/cwmp
    touch /var/lib/cwmp/restore
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        restart
        ;;
    backup)
        backup
        ;;
    restore)
        restore
        ;;
    reset)
        rm -f /etc/config/cwmp-settings.odl
        ;;
    debuginfo)
        pcb_debug_info $name $component $datamodel
        ;;
    log)
       action=$2
       if [ -n "$action" ]; then
           pcb_log $name $action $trace_zones
       else
           pcb_log $name enable $trace_zones
       fi
       ;;
    *)
        ;;
esac

