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

START=90
STOP=15
USE_PROCD=1
NAME=xjay

GENERATE_CONF="/usr/share/xjay/utils/gen_config.lua"
GENERAL_FIRST_SECTION=""
GENERAL_FIRST_SECTION=""
DEFAULT_INBOUND_CFG=""
DEFAULT_OUTBOUND_CFG=""

# call back funtion to invoked when config_load parse each config
# here we parse the first general section
config_cb(){
        local type="$1"
        local name="$2"
        if [ "$type" == "general" ] && [ "$GENERAL_FIRST_SECTION" == "" ]; then
                GENERAL_FIRST_SECTION="$name"
        elif [ "$type" == "inbound" ] && [ "$INBOUND_FIRST_SECTION" == "" ]; then
                INBOUND_FIRST_SECTION="$name"
        elif [ "$type" == "outbound" ] && [ "$OUTBOUND_FIRST_SECTION" == "" ]; then
                OUTBOUND_FIRST_SECTION="$name"
        elif [ "$type" == "misc" ] && [ "$MISC_FIRST_SECTION" == "" ]; then
                MISC_FIRST_SECTION="$name"
        fi
}

log_procd_set_param() {
    local type="$1"
    shift
    logger -st xjay[$$] -p4 "Using procd_set_param $type" "$@"
}

start_xjay() {
    logger -st xjay[$$] -p4 "Starting Xray from $1"
    procd_open_instance
    procd_set_param respawn 1 1 0
    procd_set_param command $1
    procd_append_param command run
    procd_append_param command -confdir
    procd_append_param command /var/etc/xjay
    procd_set_param limits nofile="163840 327680"
    procd_set_param env XRAY_LOCATION_ASSET=/usr/share/xray
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_set_param file /etc/config/xjay
    procd_set_param pidfile /var/run/xjay.pid
    procd_close_instance
}

gen_config_file() {
    mkdir -p /var/etc/xjay
    rm -f /var/etc/xjay/*
    logger -st xjay[$$] -p4 "Generating Xray configuration files..."
    /usr/bin/lua ${GENERATE_CONF} > /var/etc/xjay/config.json
}

start_service() {
    config_load $NAME

    # if not enabled exit without doing anything
    local enabled=""
    local xray_path=""
    config_get enabled $GENERAL_FIRST_SECTION enabled
    [ "$enabled" != "true" ] && logger -st xjay[$$] -p4 "Diabled, exiting..." && return

    # if default inbound is not set or deleted, then exit
    local default_inbound=""
    config_get default_inbound $INBOUND_FIRST_SECTION default_inbound
    [ "$default_inbound" == "" ] && logger -st xjay[$$] -p4 "No default inbound set, exiting..." && return

    # if default outbound is not set or deleted, then exit
    local default_outbound=""
    config_get default_outbound $OUTBOUND_FIRST_SECTION default_outbound
    [ "$default_outbound" == "" ] && logger -st xjay[$$] -p4 "No default outbound set, exiting..." && return

    # find default inbound by matching tag
    # we do not use config id because when delete an inbound
    # the config id of default inbound may be changed
    find_default_inbound_cfg() {
        local cfg_id="$1"
        local tag=$(config_get $cfg_id tag)
        if [ "$tag" = "$default_inbound" ]; then
            DEFAULT_INBOUND_CFG="$cfg_id"
            logger -st xjay[$$] -p4 "Using default inbound: [$tag]..."
        fi
    }
    config_foreach find_default_inbound_cfg inbound_service
    [ "$DEFAULT_INBOUND_CFG" == "" ] && logger -st xjay[$$] -p4 "Default inbound not found, exiting..." && return

    # find default outbound by matching tag
    # we do not use config id because when delete an outbound
    # the config id of default outbound may be changed
    find_default_outbound_cfg() {
        local cfg_id="$1"
        local tag=$(config_get $cfg_id tag)
        if [ "$tag" = "$default_outbound" ]; then
            DEFAULT_OUTBOUND_CFG="$cfg_id"
        fi
    }
    config_foreach find_default_outbound_cfg outbound_server
    [ "$DEFAULT_OUTBOUND_CFG" == "" ] && \
    [ "$default_outbound" != "direct" ] && \
    [ "$default_outbound" != "blackhole" ] && \
    logger -st xjay[$$] -p4 "Default outbound not found, exiting..." && return
    logger -st xjay[$$] -p4 "Using default outbound: [$default_outbound]..."


    # check xray bin and start it
    mkdir -p /var/run /var/etc
    config_get xray_path $MISC_FIRST_SECTION xray_path
    command -v ${xray_path} > /dev/null 2>&1 || return 1
    gen_config_file
    start_xjay ${xray_path}

    # set up firewall rules for routing
    /usr/share/xjay/firewall/firewall_xjay.sh "$DEFAULT_INBOUND_CFG"

    # restart xjay when wan IP changed
    # to ensure new WAN IP will be added to rule
    ln -s /usr/share/xjay/firewall/xjay-iface-wan-ip.hotplug /etc/hotplug.d/iface/90-xjay-iface-wan-ip
}

stop_service() {
    rm -rf /etc/hotplug.d/iface/90-xjay-iface-wan-ip
    /usr/share/xjay/firewall/firewall_reset.sh
}

reload_service() {
    stop
    start
}

service_triggers() {
    procd_add_reload_trigger "xjay"
}
