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

START=99

set_switch_on="uci set http_client_detect.settings.enabled=1"
set_switch_off="uci set http_client_detect.settings.enabled=0"
set_switch_commit="uci commit http_client_detect"
APP_CTF_MGR="/usr/sbin/ctf_manger.sh"
service_name="http_client_detect"
fastpath=""

export EXTRA_COMMANDS=" on off "
export EXTRA_HELP="	on	Switch to the start state and start
	off	Switch to the stop state and stop"

create_ctf_mgr_entry()
{
    uci -q batch <<EOF > /dev/null
set ctf_mgr.$service_name=service
set ctf_mgr.$service_name.http_switch=off
commit ctf_mgr
EOF
}

start() {
    switch=`uci get http_client_detect.settings.enabled -q`
    if [ $switch -ne "1" ]; then
        #if not enabled, just exit
        return 0
    fi

    fastpath=`uci get misc.http_proxy.fastpath -q`
    [ -z $fastpath ] && return 0

    if [ $fastpath == "ctf" ]; then
        if [ -f $APP_CTF_MGR ]; then
            is_exist=`uci get ctf_mgr.$service_name -q`
            if [ $? -eq "1" ]; then
                create_ctf_mgr_entry
            fi
            $APP_CTF_MGR $service_name http on
        fi
    elif [ $fastpath == "hwnat" ]; then
        echo "http client detect: can work with hw_nat."
    else
        echo "http client detect: unknown fastpath! Treat as std!"
    fi
    insmod nf_conn_ext_http >/dev/null 2>&1
    insmod nf_tcp_proxy >/dev/null 2>&1
    # ensure start switch
    echo "1" > /proc/sys/net/ipv4/tcp_proxy_switch
    insmod http_identify >/dev/null 2>&1
    #avoid to hold start procedure, use nohup
    /usr/sbin/http_dpi >/dev/null 2>&1 &

    return 0
}

stop() {
    killall http_dpi >/dev/null 2>&1
    rmmod http_identify >/dev/null 2>&1
    rmmod nf_tcp_proxy >/dev/null 2>&1

    fastpath=`uci get misc.http_proxy.fastpath -q`
    [ -z $fastpath ] && return 0

    if [ $fastpath == "ctf" ]; then
        if [ -f $APP_CTF_MGR ]; then
            $APP_CTF_MGR $service_name http off
        fi
    elif [ $fastpath == "hwnat" ]; then
        echo "http client detect stopped."
    else
        echo "http client detect: unknown fastpath! Treat as std!"
    fi
    return 0
}

off() {
    $set_switch_off >/dev/null 2>&1
    $set_switch_commit >/dev/null 2>&1
    stop
    return $?
}

on() {
    $set_switch_on >/dev/null 2>&1
    $set_switch_commit >/dev/null 2>&1

    start
    return $?
}

