#!/bin/bash

# qt-proxy sysVinit config file

. /etc/init.d/functions

# Path to the qt proxy config file.
CONFIG_FILE_PATH="/etc/qingtian/enclave/qt-proxy.conf"

# Path to the qt proxy log file.
LOG_FILE_PATH="/var/log/qt_proxy.log"

# Maximum number of channels supported.
export MAX_CHANNEL_COUNT=2

export CHANNEL_COUNT=0

# Config variables to be populated when parsing the config file.
declare -A CONFIG

function init_config() {
    local channels=()

    for ((i=1; i<=CHANNEL_COUNT; i++)); do
        channels+=("channel$i")
    done

    for channel in "${channels[@]}"; do
        CONFIG[$channel, local_port]=
        CONFIG[$channel, remote_addr]=
        CONFIG[$channel, remote_port]=
    done

    CONFIG[ipv6]=
}

function parse_config {
    local count=0
    local channels=()
    while read line; do
        count=$((count+1))
        # Skip comment lines and blank lines
        echo "$line" | grep -Eq "^$|^#" && continue
        if [[ $line =~ ^\[(.*)\]$ ]]; then
            # Resolve channel name
            channel=${BASH_REMATCH[1]}
            CHANNEL_COUNT=$((CHANNEL_COUNT+1))
            if [[ $CHANNEL_COUNT -gt $MAX_CHANNEL_COUNT ]]; then
                echo "Skipping channel $channel in $CONFIG_FILE_PATH:$count - only up to $MAX_CHANNEL_COUNT channels are supported"
                break
            fi
            continue
        fi
        init_config
    done < "$CONFIG_FILE_PATH"
    while read line; do
        # Skip comment lines and blank lines
        echo "$line" | grep -Eq "^$|^#" && continue
        if [[ $line =~ ^\[(.*)\]$ ]]; then
            channel=${BASH_REMATCH[1]}
            continue
        fi
        local key
        key=$(echo "$line" | cut -d: -f1 | egrep -io "^([-_a-z0-9])+")
        if [[ $key == "ipv6" ]]; then
            [[ -z ${CONFIG[$key]+x} ]] && echo "Error in $CONFIG_FILE_PATH:$count - unexpected: $key"
            local value
            value=$(echo "$line" | sed -E "s/^.+://" | sed -E "s/\\s+\"?//" | sed -E "s/\"?\$//")
            [[ -z $value ]] && echo "Error in $CONFIG_FILE_PATH:$count - missing value for $key"
            ipv6=$(echo $value | cut -d: -f1)
            CONFIG[$key]="$ipv6"
            echo "CONFIG[$key]=$value"
        else
            [[ -z ${CONFIG[$channel, $key]+x} ]] && echo "Error in $CONFIG_FILE_PATH:$count - unexpected: $key"
            local value
            value=$(echo "$line" | sed -E "s/^.+://" | sed -E "s/\\s+\"?//" | sed -E "s/\"?\$//")
            [[ -z $value ]] && echo "Error in $CONFIG_FILE_PATH:$count - missing value for $key"
            CONFIG[$channel, $key]="$value"
            echo "CONFIG[$channel, $key]=$value"
        fi
    done < "$CONFIG_FILE_PATH"
    # Some trivial config validation.
    for ((i=1; i<=CHANNEL_COUNT; i++)); do
        channels+=("channel$i")
    done
    for channel in "${channels[@]}"; do
        [[ -z ${CONFIG[$channel, local_port]} ]] && \
            echo "Config error: missing $channel local vsock port (\`local_port\`)." && exit 1
        [[ -z ${CONFIG[$channel, remote_addr]} ]] && \
            echo "Config error: missing $channel remote address (\`remote_addr\`)." && exit 1
        [[ -z ${CONFIG[$channel, remote_port]} ]] && \
            echo "Config error: missing $channel remote port (\`remote_port\`)." && exit 1
        echo "$channel local_port: ${CONFIG[$channel, local_port]}"
        echo "$channel remote_addr: ${CONFIG[$channel, remote_addr]}"
        echo "$channel remote_port: ${CONFIG[$channel, remote_port]}"
    done
    [[ -z ${CONFIG[ipv6]} ]] && \
        echo "Config error: missing ipv6 support (\`ipv6\`)." && exit 1
    echo "ipv6: ${CONFIG[ipv6]}"
}

start() {
    parse_config
    proxy_pid="$(pidof qt_proxy)"
    if [ ${proxy_pid[@]} ]; then
        echo "The qt-proxy process is existed, please clear ..."
        exit 1
    fi
    echo "Starting qt-proxy service ..."
    local channels=()
    for ((i=1; i<=CHANNEL_COUNT; i++)); do
        channels+=("channel$i")
    done
    if [ ${CONFIG[ipv6]} == 1 ]; then
        for channel in "${channels[@]}"; do
            /usr/local/bin/qingtian/enclave/qt_proxy -l ${CONFIG[$channel, local_port]} -a ${CONFIG[$channel, remote_addr]} -p ${CONFIG[$channel, remote_port]} -6 &
        done
    elif [ ${CONFIG[ipv6]} == 0 ]; then
        for channel in "${channels[@]}"; do
            /usr/local/bin/qingtian/enclave/qt_proxy -l ${CONFIG[$channel, local_port]} -a ${CONFIG[$channel, remote_addr]} -p ${CONFIG[$channel, remote_port]} &
        done
    else
        echo "invalid ipv6 value: ${CONFIG[ipv6]}, only support 0 or 1"
        exit 1
    fi
    proxy_pid="$(pidof qt_proxy)"
    echo "proxy pid = [$proxy_pid]"
    if [ ${#proxy_pid[@]} -lt $CHANNEL_COUNT ]; then
        echo 'channel count = ['"${#proxy_pid[@]}"']'
        sleep 1
        echo 'try to get pid again ....'
        proxy_pid=($(pidof qt_proxy))
        echo '[try value]proxy pid = ['"${proxy_pid[@]}"']'
        if [ ${#proxy_pid[@]} -lt $CHANNEL_COUNT ]; then
            echo 'The qt-proxy service start fail, please check '${LOG_FILE_PATH}''
            exit 1
        fi
    fi
    touch /var/lock/subsys/qt-proxy
}

stop() {
    echo "Stopping qt-proxy service ..."
    killproc qt_proxy
    rm -f /var/lock/subsys/qt-proxy
    rm -f /var/run/enclave_proxy_*.socket
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload|condrestart)
        stop
        start
        ;;
    status)
        status qt-proxy
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|reload|condrestart|status}"
        exit 1
esac

exit 0
