#!/usr/bin/env bash
. "$(dirname "${BASH_SOURCE[0]}")/lib/harness.sh"
set -eo pipefail

GENERATOR_UC="$TACHYON_LIB/tachyon_core/generator.uc"
VALIDATOR_UC="$TACHYON_LIB/config/validator.uc"

generate_config() {
  local fixture="$1"
  local output="$2"
  mkdir -p "${output}.section-cache"
  ucode -L "$TACHYON_LIB" "$GENERATOR_UC" generate-config-fixture \
    "$fixture" "$output" "127.0.0.1"
}

validate_fixture() {
  local fixture="$1"
  TACHYON_LIB="$TACHYON_LIB" ucode -L "$TACHYON_LIB" "$VALIDATOR_UC" \
    validate-runtime-fixture "$fixture" "{}"
}

cat >"$WORK_DIR/fixture.json" <<'JSON'
{
  "settings": {
    ".name": "settings",
    ".type": "settings",
    "dns_server": [ "77.88.8.8" ],
    "bootstrap_dns_server": [ "77.88.8.8" ]
  },
  "section": [
    {
      ".name": "proxy",
      ".type": "section",
      "enabled": "1",
      "action": "proxy",
      "outbound_jsons": [
        "{\"type\":\"vless\",\"tag\":\"Alpha\",\"server\":\"alpha.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000001\",\"tls\":{\"enabled\":true}}",
        "{\"type\":\"vless\",\"tag\":\"Beta\",\"server\":\"beta.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000002\",\"transport\":{\"type\":\"ws\"},\"tls\":{\"enabled\":true,\"reality\":{\"enabled\":true}}}",
        "{\"type\":\"vmess\",\"tag\":\"Gamma\",\"server\":\"gamma.example\",\"server_port\":443,\"uuid\":\"00000000-0000-4000-8000-000000000003\",\"transport\":{\"type\":\"grpc\"}}",
        "{\"type\":\"trojan\",\"tag\":\"Delta\",\"server\":\"delta.example\",\"server_port\":443,\"password\":\"secret\",\"transport\":{\"type\":\"xhttp\"},\"tls\":{\"enabled\":true}}",
        "{\"type\":\"http\",\"tag\":\"Echo\",\"server\":\"echo.example\",\"server_port\":8080}"
      ]
    }
  ],
  "urltest": [
    {
      ".name": "and_filter",
      ".type": "urltest",
      "section": "proxy",
      "name": "AND filter",
      "filter_mode": "mixed",
      "include_regex": [ "Alpha|Beta|Gamma|Delta" ],
      "include_proxy_parameters": "1",
      "include_protocols": [ "vless", "vmess" ],
      "include_transports": [ "tcp", "ws", "grpc" ],
      "include_securities": [ "tls", "reality", "none" ],
      "exclude_regex": [ "Alpha" ],
      "exclude_proxy_parameters": "1",
      "exclude_securities": [ "reality" ],
      "include_ports": [ "443" ],
      "exclude_ports": [ "8080" ]
    },
    {
      ".name": "parameters_only",
      ".type": "urltest",
      "section": "proxy",
      "name": "Parameters only",
      "filter_mode": "include",
      "include_proxy_parameters": "1",
      "include_protocols": [ "http" ],
      "include_transports": [ "tcp" ],
      "include_securities": [ "none" ]
    },
    {
      ".name": "port_range_filter",
      ".type": "urltest",
      "section": "proxy",
      "name": "Port range filter",
      "filter_mode": "include",
      "include_proxy_parameters": "1",
      "include_ports": [ "8000-9000" ]
    }
  ],
  "priority_group": [
    {
      ".name": "pg_parameters",
      ".type": "priority_group",
      "section": "proxy",
      "name": "Parameter priority"
    }
  ],
  "priority_level": [
    {
      ".name": "pl_grpc",
      ".type": "priority_level",
      "group": "pg_parameters",
      "name": "gRPC VMess",
      "order": "0",
      "filter_mode": "include",
      "include_proxy_parameters": "1",
      "include_protocols": [ "vmess" ],
      "include_transports": [ "grpc" ],
      "include_securities": [ "none" ],
      "include_ports": [ "443" ]
    },
    {
      ".name": "pl_mixed",
      ".type": "priority_level",
      "group": "pg_parameters",
      "name": "Mixed VLESS",
      "order": "1",
      "filter_mode": "mixed",
      "regex": [ "Alpha|Beta" ],
      "include_proxy_parameters": "1",
      "include_protocols": [ "vless" ],
      "exclude_regex": [ "Alpha" ],
      "exclude_proxy_parameters": "1",
      "exclude_securities": [ "reality" ]
    },
    {
      ".name": "pl_xhttp",
      ".type": "priority_level",
      "group": "pg_parameters",
      "name": "XHTTP Trojan",
      "order": "2",
      "filter_mode": "include",
      "include_proxy_parameters": "1",
      "include_protocols": [ "trojan" ],
      "include_transports": [ "xhttp" ],
      "include_securities": [ "tls" ],
      "include_ports": [ "400-500" ]
    },
    {
      ".name": "pl_remaining",
      ".type": "priority_level",
      "group": "pg_parameters",
      "name": "Remaining",
      "order": "3",
      "filter_mode": "disabled"
    }
  ]
}
JSON

validate_fixture "$WORK_DIR/fixture.json" >/dev/null || fail "valid proxy parameter filters"
generate_config "$WORK_DIR/fixture.json" "$WORK_DIR/config.json"

ucode -e '
let fs = require("fs");
function fail(message) { die(message + "\n"); }
function outbound_by_tag(config, tag) {
    for (let outbound in config.outbounds || [])
        if (outbound && outbound.tag == tag)
            return outbound;
    return null;
}
function assert_array(value, expected, label) {
    value = value || [];
    if (length(value) != length(expected))
        fail(label + " length mismatch: " + sprintf("%J", value));
    for (let i = 0; i < length(expected); i++)
        if (value[i] != expected[i])
            fail(label + " mismatch: " + sprintf("%J", value));
}
let config = json(fs.readfile(ARGV[0]));
let cache = json(fs.readfile(ARGV[1]));
assert_array(outbound_by_tag(config, "proxy-urltest-and_filter-out").outbounds, [ "Gamma" ], "URLTest AND/OR filter");
assert_array(outbound_by_tag(config, "proxy-urltest-parameters_only-out").outbounds, [ "Echo" ], "URLTest parameter-only filter");
assert_array(outbound_by_tag(config, "proxy-urltest-port_range_filter-out").outbounds, [ "Echo" ], "URLTest port-range filter");
assert_array(outbound_by_tag(config, "proxy-priority-pg_parameters-out").outbounds,
    [ "Gamma", "Delta", "Alpha", "Beta", "Echo" ], "Priority parameter filters");
let priority_levels = ((cache.priorityGroups || {})["proxy-priority-pg_parameters-out"] || {}).levels || [];
assert_array(priority_levels[1].outbounds, [], "Priority exclusion OR filter");

let metadata = cache.outboundMetadata || {};
if (metadata.protocols.Alpha != "vless" || metadata.protocols.Echo != "http")
    fail("protocol metadata was not normalized");
if (metadata.transports.Alpha != "tcp" || metadata.transports.Beta != "ws" || metadata.transports.Delta != "xhttp")
    fail("transport metadata was not normalized");
if (metadata.securities.Alpha != "tls" || metadata.securities.Beta != "reality" || metadata.securities.Gamma != "none")
    fail("security metadata was not normalized");
if (metadata.ports.Alpha != "443" || metadata.ports.Echo != "8080")
    fail("port metadata was not normalized");
' "$WORK_DIR/config.json" "$WORK_DIR/config.json.section-cache/proxy.json" ||
  fail "URLTest and Priority proxy parameter filtering"

node - "$WORK_DIR/fixture.json" "$WORK_DIR/invalid.json" <<'JS'
const fs = require('fs');
const fixture = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
fixture.urltest[0].include_protocols = ['invalid'];
fs.writeFileSync(process.argv[3], JSON.stringify(fixture));
JS

if validate_fixture "$WORK_DIR/invalid.json" >/dev/null 2>&1; then
  fail "invalid proxy protocol should be rejected"
fi

node - "$WORK_DIR/fixture.json" "$WORK_DIR/invalid_port.json" <<'JS'
const fs = require('fs');
const fixture = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
fixture.urltest[0].include_ports = ['70000'];
fs.writeFileSync(process.argv[3], JSON.stringify(fixture));
JS

if validate_fixture "$WORK_DIR/invalid_port.json" >/dev/null 2>&1; then
  fail "port 70000 should be rejected"
fi

node - "$WORK_DIR/fixture.json" "$WORK_DIR/invalid_port_range.json" <<'JS'
const fs = require('fs');
const fixture = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
fixture.urltest[0].include_ports = ['500-100'];
fs.writeFileSync(process.argv[3], JSON.stringify(fixture));
JS

if validate_fixture "$WORK_DIR/invalid_port_range.json" >/dev/null 2>&1; then
  fail "inverted port range 500-100 should be rejected"
fi

node - "$WORK_DIR/fixture.json" "$WORK_DIR/invalid_port_zero.json" <<'JS'
const fs = require('fs');
const fixture = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
fixture.urltest[0].include_ports = ['0'];
fs.writeFileSync(process.argv[3], JSON.stringify(fixture));
JS

if validate_fixture "$WORK_DIR/invalid_port_zero.json" >/dev/null 2>&1; then
  fail "port 0 should be rejected"
fi

printf 'proxy parameter filter regression tests passed\n'
