#! /bin/bash



# BEGIN {Variable Definition}
save_info_file="/tmp/$(basename "$0").save"
at_device=''
proc_id=-1
module_type=0
module_name[0]='UNDEFINED MODULE'
module_name[1]='RM500Q'
module_name[2]='RM500U'
module_name[3]='FM160'
module_name[4]='FM650'
module_name[5]='FM650-CN'
module_name[6]='SRM821'
module_name[7]='R8200C'
device_num=-1
dail_func=''
is_off=0

# END {Variable Definition}

# static
is_exist_dev() {
    local count it
    count=0
    for it in /dev/ttyUSB*; do
        let count++
    done
    if ((count < 3)); then
        return 1
    fi
    return 0
}

# static
disable_4g_5g() {
    sleep 1
}

# disable_4g_5g() {
#     ## disable 4G/5G PWR
#     echo 1 > /sys/class/gpio/gpio53/value
#     sleep 1
# }

# enable_4g_5g 4g/5g
# static
enable_4g_5g() {
    if (("$#" != 1)); then
        return 1
    fi
    local it
    echo "enable_4g_5g $1"
    ## enable 4G/5G PWR
    if [[ ! -e "/tmp/isnetd.flag" ]]; then
        # echo 53 > /sys/class/gpio/export
        # echo out > /sys/class/gpio/gpio53/direction
        # echo 1 > /sys/class/gpio/gpio53/value
        sleep 0.5
        touch /tmp/isnetd.flag
    fi
    # echo 0 > /sys/class/gpio/gpio53/value
    echo 'Wait device ttyUSB ...'
    for ((it=0; it<60; it++)); do
        if is_exist_dev; then
            break
        fi
        printf 'Count %02d\r' "${it}"
        sleep 1
    done
    printf '\n'
    if ((it == 60)); then
        echo "Wait device ttyUSB timeout!"
        return 2
    fi
    echo "Found device ttyUSB"
    return 0
}

# static
up_usb0() {
    local result
    result="$(ip a | grep usb0 | grep -c DOWN)"
    if (( result == 1 )); then
        ifconfig usb0 up
    fi
}

# static
is_exist_ip() {
    local result
    result="$(ifconfig usb0 | grep 'inet ' | awk -F'.' '{print NF}')"
    if ((result < 4)); then
        return 1
    fi
    return 0
}

# use: is_available_at_device '/dev/ttyUSB0'
# static
is_available_at_device() {
    if (("$#" != 1)); then
        return 1
    fi
    local device result count
    device="$1"
    echo "device: ${device}"
    result="$(sendat 'AT' -d "${device}" -b 115200)"
    printf '[%d] result: (' "${LINENO}"
    echo -e "${result}"
    printf ')\n'
    count="$(echo ${result} | grep -c 'OK')"
    if ((count != 1)); then
        return 2
    fi
    return 0
}

# static
judge_module_type() {
    local result
    # RM500Q lsusb 2c7c:0800
    result=$(lsusb | grep -c '2c7c:0800')
    if ((result == 1)); then
        return 1
    fi
    # RM500U lsusb 2c7c:0900
    result=$(lsusb | grep -c '2c7c:0900')
    if ((result == 1)); then
        return 2
    fi
    # FM160  lsusb 2cb7:0105
    result=$(lsusb | grep -c '2cb7:0105')
    if ((result == 1)); then
        return 3
    fi
    # FM650  lsusb 2cb7:0a05
    result=$(lsusb | grep -c '2cb7:0a05')
    if ((result == 1)); then
        return 4
    fi
    # FM650-CN lsusb 2cb7:0a04
    result=$(lsusb | grep -c '2cb7:0a04')
    if ((result == 1)); then
        return 5
    fi
    # SRM821 lsusb 2dee:4d52 NCM
    result=$(lsusb | grep -c '2dee:4d53')
    if ((result == 1)); then
        return 6
    fi
    result=$(lsusb | grep -c '2dee:4d52')
    if ((result == 1)); then
        return 6
    fi
    result=$(lsusb | grep -c '2dee:4d51')
    if ((result == 1)); then
        return 6
    fi
    # R8200C lsusb 1782:4038 RNDIS
    result=$(lsusb | grep -c '1782:4038')
    if ((result == 1)); then
        return 7
    fi
}

run_RM500Q() {
    if (("$#" != 1)); then
        return 1
    fi
    if (($1 == 1)); then
        /usr/bin/quectel-CM &
        proc_id="$!"
    elif (($1 == 0)); then
        destroy
    else
        return 3
    fi
    return 0
}

run_RM500U() {
    if (("$#" != 1)); then
        return 1
    fi
    if (($1 == 1)); then
        /usr/bin/quectel-CM &
        proc_id="$!"
    elif (($1 == 0)); then
        destroy
    fi
    return 0
}

run_FM160() {
    if (("$#" != 1)); then
        return 1
    fi
    local result count it
    if (($1 == 1)); then
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT+GTRNDIS=1' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
        # if ((it == 10)); then
        #     return 2
        # fi
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT+GTUSBMODE=18' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
        # if ((it == 10)); then
        #     return 2
        # fi
        # sleep 3
        busybox udhcpc -i usb0 &
        proc_id="$!"
    elif (($1 == 0)); then
        destroy
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT+GTRNDIS=0' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
        
    else
        return 5
    fi
    return 0
}

run_FM650() {
    if (("$#" != 1)); then
        return 1
    fi
    local it result count
    if (($1 == 1)); then
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT+GTRNDIS=1,1' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
        # if ((it == 10)); then
        #     return 2
        # fi
        # sleep 3
        busybox udhcpc -i usb0 &
        proc_id="$!"
    elif (($1 == 0)); then
        destroy
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT+GTRNDIS=1,0' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done  
    else
        return 4
    fi
    return 0
}


run_SRM821() {
    if (("$#" != 1)); then
        return 1
    fi
    local it result count
    if (($1 == 1)); then
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT^NDISDUP=1,1' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
        # if ((it == 10)); then
        #     return 2
        # fi
        # sleep 3
        busybox udhcpc -i usb0 &
        proc_id="$!"
    elif (($1 == 0)); then
        destroy
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT^NDISDUP=1,0' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
    else
        return 4
    fi
    return 0
}

# AT+CFUN=1 active
# AT+CFUN=1,1 restart module
run_R8200C() {
    if (("$#" != 1)); then
        return 1
    fi
    local it result count
    if (($1 == 1)); then
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT^NDISDUN="usb0",1,1' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
        # if ((it == 10)); then
        #     return 2
        # fi
        # sleep 3
        busybox udhcpc -i usb0 &
        proc_id="$!"
    elif (($1 == 0)); then
        destroy
        for ((it=0; it<10; it++)); do
            result="$(sendat 'AT^NDISDUN="usb0",0,1' -d ${at_device} -b 115200)"
            printf '[%d] result: (' "${LINENO}"
            echo -e "${result}"
            printf ')\n'
            count="$(echo ${result} | grep -c 'OK')"
            if ((count >= 1)); then
                break
            fi
            sleep 3
        done
    else
        return 4
    fi
    return 0
}

dial_start() {
    echo "${module_name["${module_type}"]} dial start"
    if ! ${dail_func} 1; then
        echo "${module_name["${module_type}"]} dial start failed"
        return 1
    fi
    return 0
}

dial_stop() {
    echo "${module_name["${module_type}"]} dial stop"
    if ! ${dail_func} 0; then
        echo "${module_name["${module_type}"]} dial stop failed"
        return 1
    fi
    return 0
}

get_device() {
    if ((module_type == 0 || device_num == -1)); then
        return 1
    fi
    local count
    # echo "get at_device ..."
    count=0
    for it in /dev/ttyUSB*; do
        if [[ "${it:$((${#it} - 1)):1}" != '*' ]]; then
            let count++
            if ((count == device_num)); then
                at_device="${it}"
            fi
        fi
    done
    if [[ "${at_device}" == '' ]] || ((count == 0)); then
        # echo "get at_device failed!"
        return 2
    fi
    # echo "at_device: ${at_device}"
    return 0
}

judge_module() {
    local it count
    # echo "judge_module_type"
    judge_module_type
    module_type="$?"
        echo "mt: $module_type"
    # echo "module_type: ${module_name["${module_type}"]}"
    if ((module_type == 1)); then
        # RM500Q
        dail_func="run_RM500Q"
        device_num=3
    elif ((module_type == 2)); then
        # RM500U
        dail_func="run_RM500U"
        device_num=3
    elif ((module_type == 3)); then
        # FM160
        dail_func="run_FM160"
        device_num=3
    elif ((module_type == 4)); then
        # FM650
        dail_func="run_FM650"
        device_num=1
    elif ((module_type == 5)); then
        # FM650-CN
        dail_func="run_FM650"
        device_num=2
    elif ((module_type == 6)); then
        # SRM821
        dail_func="run_SRM821"
        device_num=2
    elif ((module_type == 7)); then
        # R8200C
        dail_func="run_R8200C"
        device_num=5
    else
        return 1
    fi
    if [[ "${dail_func}" == '' ]] || ((device_num == -1)); then
        return 2
    fi
    return 0
}

destroy() {
    if ((proc_id != -1)) && kill -0 "${proc_id}" &> /dev/null; then
        kill -9 "${proc_id}"
        proc_id=-1
        printf '%d' "${proc_id}" > "${save_info_file}"
    fi
}

# BEGIN {__MAIN__}

if (("$#" != 0)); then
    case "$1" in
        5[Gg])
            enable_4g_5g '5g'
            exit 0
            ;;
        4[Gg])
            enable_4g_5g '4g'
            exit 0
            ;;
        judge)
            judge_module
            get_device
            echo "module: ${module_name["${module_type}"]}"
            echo "device: ${at_device}"
            exit 0
            ;;
        reset)
            # is_reset=1
            echo "reset. disable_4g_5g."
            disable_4g_5g
            ;;
        on)
            is_off=0
            echo "is_off=0"
            ;;
        off)
            is_off=1
            echo "is_off=1"
            ;;
        pid)
            if test -e "${save_info_file}"; then
                proc_id="$(cat "${save_info_file}")"
                printf 'proc_id: %d' "${proc_id}"
                if kill -0 "${proc_id}" &> /dev/null; then
                    printf ' is valid.'
                else 
                    printf ' is invalid!'
                fi
                printf '\n'
            fi
            exit 0
            ;;
        restart)
            # TODO:
            exit 0
            ;;
        *)
            echo "Hello,World!"
            exit 0
            ;;
    esac
fi

if test -e "${save_info_file}"; then
    proc_id="$(cat "${save_info_file}")"
    echo "proc_id: ${proc_id}"
fi

if ((is_off == 0)); then
    destroy
    if ! enable_4g_5g '5g'; then
        echo 'enable_4g_5g failed!'
        exit 1
    fi
fi

up_usb0

if ! judge_module; then
    echo 'judge_module failed!'
    exit 2
fi

if ! get_device; then
    echo 'get_device failed!'
    exit 3
fi

for i in $(seq 1 30); do 
    if is_available_at_device "${at_device}"; then
        break
    fi
    sleep 1
done

if ((i == 30)); then
    echo 'send AT failed!'
    exit 4
fi

if ((is_off == 1)); then
    dial_stop
    disable_4g_5g
    exit 0
fi

if ! dial_start; then
    exit 5
fi

printf '%d' "${proc_id}" > "${save_info_file}"

for i in $(seq 1 30); do 
    if is_exist_ip "${at_device}"; then
        break
    fi
    sleep 1
done

if ((i == 30)); then
    echo 'get ip failed!'
    destroy
    exit 6
fi

exit 0

# END {__MAIN__}
