#!/bin/sh /etc/rc.common

START=50

USE_PROCD=1
PROG="/usr/bin/modbusslave"
CONFIGFILE="/etc/modslave/modslave.conf"
CRONTTAB_PATH="/etc/crontabs/root"
get_interface_ip () {
    local cfg="$1"
    config_get types "$cfg" types
    #types=`uci get modslave.@connection[0].types`
    if [ "$types" == "internal" ];then
        config_get ip "$cfg" internal_ip
        #ip=`uci get modslave.@connection[0].internal_ip`
        if [ "$ip" == "LAN" ]; then
            ip=`uci get network.lan.ipaddr`
        elif [ "$ip" == "" ]; then
            ip="127.0.0.1"
        else
            ifconfig eth1 $ip
        fi
        echo $ip

    else
        count=1
        while [ $count -le 5 ]
        do
            interface=`uci get mwan3.m$count.interface`
            if [[ "$interface" = "wan" ]] || [[ "$interface" = "wwan" ]] || [[ "$interface" = "cellular" ]]
                then
                status=`/usr/sbin/get_interface_status.sh get_"$interface"_status`
                if [ "$status" = "online" ]
                    then
                    break
                fi
            fi
            count=`expr $count + 1`
        done
        if [ "$status" = "online" ]
            then
            if [ "$interface" = "wan" ]
                then
                ip=`ifconfig eth1 | grep "inet addr" | awk -F "inet addr:" '{ print $2}'| awk -F " " '{print $1}'`
                echo $ip
            elif [ "$interface" = "wwan" ]
                then
                ip=`ifconfig wlan0 | grep "inet addr" | awk -F "inet addr:" '{ print $2}'| awk -F " " '{print $1}'`
                echo $ip    
            else

                ip=`ifconfig $(uci get network.cellular.ifname) | grep "inet addr" | awk -F "inet addr:" '{ print $2}'| awk -F " " '{print $1}'`
                echo $ip    
            fi
        else
            ip=0
            echo $ip
        fi

    fi  
}
tcp_remove_entries_crond(){
    tcp_count=1
    tcp_l_numbers=`cat /etc/crontabs/root | grep -n pin_toggler |awk -F ":" '{print$1}'`
    # reverse a string
    for i in $tcp_l_numbers
    do tcp_l_nums="$i $tcp_l_nums"
done
#echo $tcp_l_nums
while true
do
    tcp_l_num=`echo $tcp_l_nums |awk -v tcp_var=$tcp_count '{print$tcp_var}'`
    if [ "$tcp_l_num" != "" ]; then
        tcp_var=$tcp_l_num"d"

        sed -i "$tcp_var" $CRONTTAB_PATH
    else
        break
    fi
    tcp_count=`expr $tcp_count + 1`
done
}
device_configuration_add() {
    local cfg="$1"
    # echo $cfg
    config_get slaveid "$cfg" slaveid
    ip=$( get_interface_ip "$cfg")
    config_get port "$cfg" port
    # echo $slaveid $port
    echo "device_configuration,$slaveid","$ip","$port", >> $CONFIGFILE
}
reporting_parameters_add() {
    local cfg="$1"

    config_get parameter "$cfg" parameter
    config_get enabled "$cfg" enabled
    config_get start_addr "$cfg" start_addr
    echo "$parameter,$enabled","$start_addr", >> $CONFIGFILE
}

scheduled_pin_toggler_add() {
    local cfg="$1"
    echo $cfg
    config_get select "$cfg" select
    if [ "$select" != "on" ];
    then
        return
    fi
    echo $select
    config_get pin "$cfg" pin
    config_get state "$cfg" state
    config_get day_week "$cfg" day_week
    config_get month "$cfg" month   
    config_get date "$cfg" date
    config_get hour "$cfg" hour
    config_get minute "$cfg" minute

    if [ "$pin" == "DIO_1" ]; then
        if [ "$state" == "low" ]; then
            echo -e "$minute $hour $date $month $day_week echo 0 > /sys/class/gpio/do1/value        #pin_toggler_DIO_1" >> $CRONTTAB_PATH
            echo -e "$minute $hour $date $month $day_week echo 0 > /etc/modslave/gpiovaldo1_toggler  #pin_toggler_DIO_1" >> $CRONTTAB_PATH
        elif [ "$state" == "high" ]; then
            echo -e "$minute $hour $date $month $day_week echo 1 > /sys/class/gpio/do1/value        #pin_toggler_DIO_1" >> $CRONTTAB_PATH
            echo -e "$minute $hour $date $month $day_week echo 1 > /etc/modslave/gpiovaldo1_toggler  #pin_toggler_DIO_1" >> $CRONTTAB_PATH
        fi      
    fi
    if [ "$pin" == "DIO_2" ]; then
        if [ "$state" == "low" ]; then
            echo -e "$minute $hour $date $month $day_week echo 0 > /sys/class/gpio/do2/value        #pin_toggler_DIO_2" >> $CRONTTAB_PATH
            echo -e "$minute $hour $date $month $day_week echo 0 > /etc/modslave/gpiovaldo2_toggler  #pin_toggler_DIO_2" >> $CRONTTAB_PATH
        elif [ "$state" == "high" ]; then
            echo -e "$minute $hour $date $month $day_week echo 1 > /sys/class/gpio/do2/value        #pin_toggler_DIO_2" >> $CRONTTAB_PATH
            echo -e "$minute $hour $date $month $day_week echo 1 > /etc/modslave/gpiovaldo2_toggler  #pin_toggler_DIO_2" >> $CRONTTAB_PATH
        fi      
    fi
}
start_service() {
    [ -f "$CONFIGFILE" ] && rm -f "$CONFIGFILE"

    config_load modslave
    config_get_bool modslave_enable general enabled
    #echo $modslave_enable
    [ "$modslave_enable" -eq 0 ] && tcp_remove_entries_crond && /etc/init.d/cron restart && return
    #ceate folder
    [ -d /tmp/modbus_data/ ] || mkdir /tmp/modbus_data/
    procd_open_instance
    device_configuration_add connection connection
    config_foreach reporting_parameters_add reporting_parameters
    tcp_remove_entries_crond
    config_foreach scheduled_pin_toggler_add pin_toggler
    /etc/init.d/cron restart

    procd_set_param command $PROG
    procd_set_param file $CONFIGFILE
    procd_set_param respawn
    procd_close_instance
}
stop_service() {
    [ -f "$CONFIGFILE" ] && rm -f "$CONFIGFILE" && tcp_remove_entries_crond && /etc/init.d/cron restart
    return 0
}

service_triggers(){
    local script=$(readlink "$initscript")
    local name=$(basename ${script:-$initscript})
    procd_open_trigger
    procd_add_raw_trigger /etc/init.d/$name reload
    procd_close_trigger

    action=restart procd_add_reload_trigger 'modslave'

}
# service_started() {
#   procd_set_config_changed firewall
# }
