#!/bin/sh

. /usr/share/libubox/jshn.sh
. /lib/functions.sh

help() {
    cat <<_HELP_
CP210X device process.
Usage: $0 {add|remove} --slot SLOT
        --slot SLOT # the slot number

Example:
    $0 add -slot 1 
_HELP_
}

case "$1" in
add) action="$1" ;;
remove) action="$1" ;;
*)
    help
    exit 1
    ;;
esac
shift 1

while [ -n "$1" ]; do
    case $1 in
    --slot)
        slot="$2"
        shift 2
        ;;
    -*)
        help
        exit 1
        ;;
    *) break ;;
    esac
done

[ -z "$slot" ] && help && exit 1

board=$(board_name)

case "$board" in
    woolink,mt7621-64m)
        case "$slot" in
        "1")
            dev_path="/sys/devices/platform/1e1c0000.xhci/usb1/1-2/1-2.1/1-2.1:1.0"
            ;;
        "2")
            dev_path="/sys/devices/platform/1e1c0000.xhci/usb1/1-2/1-2.2/1-2.2:1.0"
            ;;
        "3")
            dev_path="/sys/devices/platform/1e1c0000.xhci/usb1/1-2/1-2.3/1-2.3:1.0"
            ;;
        esac
        ;;
    *)
        case "$slot" in
        "1")
            dev_path="/sys/devices/platform/101c0000.ehci/usb1/1-1/1-1.1/1-1.1:1.0"
            ;;
        "2")
            dev_path="/sys/devices/platform/101c0000.ehci/usb1/1-1/1-1.2/1-1.2:1.0"
            ;;
        "3")
            dev_path="/sys/devices/platform/101c0000.ehci/usb1/1-1/1-1.3/1-1.3:1.0"
            ;;
        "4")
            dev_path="/sys/devices/platform/101c0000.ehci/usb1/1-1/1-1.4/1-1.4:1.0"
            ;;
        esac
        ;;
esac

[ -z "$slot" ] && echo "slot not right" && exit 1


CFG="/tmp/ble_slot_info.json"
json_init
[ -f ${CFG} ] && json_load "$(cat ${CFG})"

case "$action" in
"add")
    echo "add $dev_path"
    DEVICE_NAME=$(ls $dev_path/bluetooth | grep hci)
    if [ -z ${DEVICE_NAME} ]; then
        echo "Warning DEVICE_NAME is empty"
        exit 1
    fi
    json_select "slot_${slot}"
    ret=$?
    if [ ${ret} -eq 0 ]; then
        # 存在
        json_add_string "ifname" ${DEVICE_NAME}
        json_select ..
    else
        json_add_object "slot_${slot}"
        json_add_string "ifname" ${DEVICE_NAME}
        json_close_object
    fi
    json_dump > ${CFG}
    logger -t Hotplug BLE Interface $DEVICE_NAME added at slot $slot
    /etc/init.d/ble_${slot} restart
    ;;
"remove")
    logger -t Hotplug "remove $dev_path"
    json_add_object "slot_${slot}"
    json_close_object
    json_dump > ${CFG}
    /etc/init.d/ble_${slot} stop
    ;;
esac
