#!/bin/sh /etc/rc.common
START=80
STOP=30
USE_PROCD=1

. /lib/functions.sh

start_service() {
    
	config_load qmodem
    config_foreach _mk_rundir modem-device
    config_get block_auto_probe main block_auto_probe 0
    config_get enable_pcie_scan main enable_pcie_scan 0
    config_get enable_usb_scan main enable_usb_scan 0
    config_get try_preset_usb main try_preset_usb 1
    config_get try_preset_pcie main try_preset_pcie 1
    #once enabled, skip all check or scan
    [ "$block_auto_probe" -eq 1 ] && return
    
    #enabled by default
    if [ "$try_preset_pcie" -eq 1 ];then
        _try_vendor_preset_pcie
    fi
    if [ "$try_preset_usb" -eq 1 ];then
        _try_vendor_preset_usb
    fi

    #not enabled by default
    if [ "$enable_usb_scan" -eq 1 ];then
        _scan_usb
    fi
    if [ "$enable_pcie_scan" -eq 1 ];then
        _scan_pcie
    fi
}

_try_vendor_preset_usb()
{
    config_foreach _try_usb_device modem-device
    config_foreach _try_usb_slot modem-slot
}

_try_vendor_preset_pcie()
{
    config_foreach _try_pcie_device modem-device
    config_foreach _try_pcie_slot modem-slot
}

_try_pcie_slot()
{
    config_get type "$1" type
    [ "$type" == "pcie" ] && _try_slot $1
}

_try_usb_slot()
{
    config_get type "$1" type
    [ "$type" == "usb" ] && _try_slot $1
}

_try_usb_device()
{
    config_get data_interface $1 data_interface
    [ "$data_interface" == "usb" ] && _try_device
}

_try_pcie_device()
{
    config_get data_interface $1 data_interface
    [ "$data_interface" == "pcie" ] && _try_device
}

_scan_usb()
{
    procd_open_instance "scan_usb"
    #delay 15 second ,scan all usb device
    procd_set_param command  "ash" "/usr/share/qmodem/modem_scan.sh" "scan" "15" "usb"
    procd_close_instance
}

_scan_pcie()
{
    procd_open_instance "scan_pcie"
    #delay 3 second ,scan all pcie device
    procd_set_param command  "ash" "/usr/share/qmodem/modem_scan.sh" "scan" "3" "pcie"
    procd_close_instance
}

_mk_rundir()
{
    modem_cfg="$1"
    mkdir -p "/var/run/qmodem/${modem_cfg}_dir"
}

_try_slot()
{
    config_get slot "$1" slot
    config_get type "$1" type
    case "$type" in
        usb)
            path="/sys/bus/usb/devices/${slot}"
            ;;
        pcie)
            path="/sys/bus/pci/devices/${slot}"
            ;;
    esac

    if [ -d "$path" ]; then
        logger -t modem_init "try modem $1"
        procd_open_instance "try_$1"
        procd_set_param command  "ash" "/usr/share/qmodem/modem_scan.sh" "add" "$slot" "$type"
        procd_close_instance
    else
        /usr/share/qmodem/modem_scan.sh disable "$slot"
    fi
}

_try_device()
{
    config_get path "$1" path
    config_get type "$1" type
    case "$type" in
        usb)
            path="/sys/bus/usb/devices/${path}"
            ;;
        pcie)
            path="/sys/bus/pci/devices/${path}"
            ;;
    esac
    if [ ! -d "$path" ]; then
        /usr/share/qmodem/modem_scan.sh disable "$1"
    fi
}
