#!/bin/sh
_port="1680"
if [ -s /etc/tachyon/tachyon.json ]; then
    _jport="$(sed -n 's/.*"web_port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' /etc/tachyon/tachyon.json | head -n 1)"
    [ -n "$_jport" ] && _port="$_jport"
elif command -v uci >/dev/null 2>&1; then
    _uport="$(uci -q get tachyon.settings.web_port 2>/dev/null)"
    case "$_uport" in
        ''|*[!0-9]*) ;;
        *) _port="$_uport" ;;
    esac
fi
_url="http://127.0.0.1:${_port}/cgi-bin/tachyon-sub${PATH_INFO:-}${QUERY_STRING:+?${QUERY_STRING}}"
_tmp="$(mktemp /tmp/tachyon-cgi-sub.XXXXXX 2>/dev/null || echo "/tmp/tachyon-cgi-sub.$$")"
trap 'rm -f "$_tmp" 2>/dev/null || true' EXIT INT TERM
_ok=0
if [ -n "${HTTP_HOST:-}" ] && [ -n "${HTTP_USER_AGENT:-}" ]; then
    curl -sS -i --max-time 10 -H "Host: ${HTTP_HOST}" -H "User-Agent: ${HTTP_USER_AGENT}" "$_url" > "$_tmp" 2>/dev/null && _ok=1
elif [ -n "${HTTP_HOST:-}" ]; then
    curl -sS -i --max-time 10 -H "Host: ${HTTP_HOST}" "$_url" > "$_tmp" 2>/dev/null && _ok=1
elif [ -n "${HTTP_USER_AGENT:-}" ]; then
    curl -sS -i --max-time 10 -H "User-Agent: ${HTTP_USER_AGENT}" "$_url" > "$_tmp" 2>/dev/null && _ok=1
else
    curl -sS -i --max-time 10 "$_url" > "$_tmp" 2>/dev/null && _ok=1
fi
if [ "$_ok" -eq 1 ]; then
    awk '
        NR==1 && $1 ~ /^HTTP\// {
            code=$2;
            sub(/^[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]*/, "");
            sub(/\r$/, "");
            printf "Status: %s %s\r\n", code, $0;
            next;
        }
        { print }
    ' "$_tmp"
    rm -f "$_tmp" 2>/dev/null || true
    exit 0
fi
rm -f "$_tmp" 2>/dev/null || true
printf "Status: 502 Bad Gateway\r\nContent-Type: text/plain\r\n\r\nTachyon web daemon unavailable\n"
exit 0
