#!/bin/sh /etc/rc.common
START=99
STOP=13
USE_PROCD=1
service="$(basename ${basescript:-$initscript})"
#脚本目录
SCRIPT_DIR="/usr/share/qmodem"

#运行目录
MODEM_RUNDIR="/var/run/qmodem"

extra_command "dial" "<modem_cfg> run dial script"
extra_command "hang" "<modem_cfg> run hang script"
extra_command "redial" "<modem_cfg> stop previous dial script. run hang script. and run dial script"
extra_command "modem_status" "<modem_cfg> Check dial script status" 


service_triggers()
{
	procd_add_reload_trigger "qmodem"

}

start_service(){
    force_stop=0
    mkdir -p $MODEM_RUNDIR
    update_modem
}

stop_service(){
    force_stop=1
    update_modem
    
}

reload_service()
{
    force_stop=0
    mkdir -p $MODEM_RUNDIR
    sleep 1
    update_modem
}


update_modem(){
    config_load qmodem
    config_get g_enabled main enable_dial
    config_foreach _update_modem modem-device
}

dial()
{
    rc_procd _dial $1
}

hang()
{
    _hang $1
}

modem_status()
{
    _modem_status $1
}

redial()
{
    hang $1
    dial $1
}

_update_modem()
{
    local target
    target=1
    config_get enabled $1 enable_dial
    config_get state $1 state
    if [ "$state" = "disabled" ] || [ "$enabled" = "0" ] || [ "$g_enabled" = "0" ] || [ "$force_stop" = "1" ];then
        target=0
    fi
    data=$(_procd_ubus_call list | jq -r  ".$service.instances.modem_$1")
    [ "$data" == "null" ] && current_status=0 || current_status=1
    logger -t qmodem_network "cfg:$1 current:$current_status;target:$target "
    if [ "$current_status" != "$target" ];then
        [ "$target" -eq 1 ] && dial $1 || hang $1
        logger -t qmodem_network "update modem cfg: $1 dial:$target"
    fi
}

_dial()
{
    procd_open_instance "modem_$1"
    procd_set_param command "/usr/share/qmodem/modem_dial.sh" "$1" dial
    procd_set_param respawn
    procd_close_instance
    logger -t qmodem_network "Modem $1 Start Dial Now"
}

_hang()
{
    procd_kill $service "modem_$1"
    /usr/share/qmodem/modem_dial.sh "$1" hang
    logger -t qmodem_network "Modem $1 Stop Dial and Hang"
}

_modem_status()
{ 
	local instances="modem_$1"
	local data
    data=$(_procd_ubus_call list | jq  -r ".$service.instances.$instances")
    [ "$data" == "null" ] && echo "$instances Not Running"  || echo "$data"
}
