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

START=90
STOP=10

# Unique path prefix so this coexists with the original hotplug-generator
IFACE_PATH="/etc/hotplug.d/iface/91-qa-hp"

add_iface_rule() {
    local enabled action command description interface target
    config_get enabled "$1" enabled
    [ "$enabled" = "0" ] && return
    config_get action "$1" action
    config_get description "$1" description
    config_get interface "$1" interface

    [ -z "$action" ] && return
    [ -z "$interface" ] && return

    target="$IFACE_PATH-$1"
    {
        echo "#!/bin/sh"
        echo "# Generated by luci-app-quickactions - do not edit directly"
        echo "# Source: /etc/config/hotplug section [$1]"
        description=$(echo $description | tr '\n' ' ')
        echo "# Description: $description"
        echo ""
        echo "if [ \"\$ACTION\" = \"$action\" ]; then"
        echo "  if [ \"\$INTERFACE\" = \"$interface\" ]; then"
    } > "$target"

    command_list=$(uci -q get "hotplug.$1.command")
    [ "${command_list:0:1}" = "'" ] && command_list="${command_list:1}"
    [ "${command_list: -1}" = "'" ] && command_list="${command_list%?}"
    i=0
    while true ; do
        i=$((i+1))
        command=$(echo "$command_list" | awk -v i=$i -F "' '" '{print $i}')
        [ -z "$command" ] && break
        echo "          $command" >> "$target"
    done

    {
        echo "  fi"
        echo "fi"
        echo "exit 0"
    } >> "$target"
    chmod 755 "$target"
}

start() {
    mkdir -p /etc/hotplug.d/iface
    rm -f "${IFACE_PATH}-"* 2>/dev/null
    config_load hotplug
    config_foreach add_iface_rule iface
    logger -t quickactions-hotplug "Handlers regenerated from /etc/config/hotplug"
}

stop() {
    rm -f "${IFACE_PATH}-"* 2>/dev/null
    logger -t quickactions-hotplug "Handlers removed"
}

restart() {
    stop
    start
}
