#!/usr/bin/env bash
set -euo pipefail

setup_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
tool_dir=$(dirname -- "$setup_dir")
iface=enx6ce4da121d35
mac=6c:e4:da:12:1d:35
connection_uuid=36bef876-11a3-3237-83b1-16b22866631f
state_dir=/var/lib/hosyu-wimax
original_hash=e91a7e5161815696b6afc732e1b7450c6ddb3e4c026cd55774e75beb5d71eaf4

if [ "$(id -u)" -ne 0 ]; then
    printf 'Run this setup with sudo.\n' >&2
    exit 1
fi

if [ "$(cat "/sys/class/net/$iface/address")" != "$mac" ]; then
    printf 'Expected WiMAX USB adapter is not connected.\n' >&2
    exit 1
fi

if [ "$(nmcli -g GENERAL.CON-UUID device show "$iface")" != "$connection_uuid" ]; then
    printf 'WiMAX connection profile changed; inspect it before applying.\n' >&2
    exit 1
fi

bash -n "$setup_dir/hosyu_post.sh"
python3 "$setup_dir/verify.py"

if [ ! -f "$state_dir/original-profile-uuid" ]; then
    if ip -4 rule show | grep -q '^17900:'; then
        printf 'Routing rule priority 17900 is already in use.\n' >&2
        exit 1
    fi
    if [ -n "$(ip -4 route show table 179 2>/dev/null || true)" ]; then
        printf 'Routing table 179 is already in use.\n' >&2
        exit 1
    fi
    if ss -H -lnt 'sport = :10809' | grep -q .; then
        printf 'Proxy port 10809 is already in use.\n' >&2
        exit 1
    fi
fi

# Hold the existing posting lock while changing routes and deploying the script.
exec 9>"$tool_dir/hosyu_post.lock"
if ! flock -w 60 9; then
    printf 'A post is still running. Retry setup after it finishes.\n' >&2
    exit 1
fi

current_hash=$(sha256sum "$tool_dir/hosyu_post.sh" | cut -d' ' -f1)
staged_hash=$(sha256sum "$setup_dir/hosyu_post.sh" | cut -d' ' -f1)
if [ "$current_hash" != "$original_hash" ] && [ "$current_hash" != "$staged_hash" ]; then
    printf 'hosyu_post.sh changed after preparation; no settings applied.\n' >&2
    exit 1
fi

install -d -m 700 "$state_dir"
install -d -m 755 /etc/hosyu-wimax
if [ ! -f "$state_dir/original-profile-uuid" ]; then
    backup_name="hosyu-wimax-before-$(date +%Y%m%d_%H%M%S)"
    nmcli connection clone uuid "$connection_uuid" "$backup_name"
    backup_uuid=$(nmcli -g connection.uuid connection show "$backup_name")
    nmcli connection modify uuid "$backup_uuid" connection.autoconnect no
    printf '%s\n' "$backup_uuid" > "$state_dir/original-profile-uuid"
    cp -p "$tool_dir/hosyu_post.sh" "$state_dir/hosyu_post.sh.before"
fi

nmcli connection modify uuid "$connection_uuid" \
    connection.id hosyu-wimax \
    connection.interface-name "$iface" \
    connection.autoconnect yes \
    802-3-ethernet.mac-address "$mac" \
    ipv4.method auto \
    ipv4.route-table 179 \
    ipv4.routing-rules 'priority 17900 from 192.168.179.0/24 table 179' \
    ipv4.never-default no \
    ipv4.ignore-auto-routes no \
    ipv4.ignore-auto-dns yes \
    ipv6.method disabled \
    ipv6.never-default yes \
    ipv6.ignore-auto-dns yes
nmcli --wait 30 connection up uuid "$connection_uuid" ifname "$iface"
sysctl -q -w "net.ipv4.conf.$iface.rp_filter=2"

python3 - <<'PY'
import ipaddress
import json
import subprocess

def ip_json(*args):
    return json.loads(subprocess.check_output(["ip", "-j", *args], text=True))

iface = "enx6ce4da121d35"
normal = ip_json("-4", "route", "get", "1.1.1.1")[0]
assert normal["dev"] == "Wan", f"Unexpected normal route: {normal}"
for family in ("-4", "-6"):
    routes = ip_json(family, "route", "show", "table", "main", "default")
    assert not any(r.get("dev") == iface for r in routes), routes
addresses = ip_json("-4", "address", "show", "dev", iface)[0]["addr_info"]
source = next(a["local"] for a in addresses if a["family"] == "inet")
assert ipaddress.ip_address(source) in ipaddress.ip_network("192.168.179.0/24")
wimax = ip_json("-4", "route", "get", "1.1.1.1", "from", source)[0]
assert wimax["dev"] == iface, f"Unexpected WiMAX route: {wimax}"
print(f"Routes verified: normal=Wan, WiMAX={iface} ({source})")
PY

if ! dpkg-query -W -f='${Status}' dante-server 2>/dev/null | grep -qx 'install ok installed'; then
    DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::ForceIPv4=true install -y --no-install-recommends dante-server
    systemctl disable --now danted.service
fi
if ! id hosyu-wimax >/dev/null 2>&1; then
    useradd --system --user-group --no-create-home --shell /usr/sbin/nologin hosyu-wimax
fi

install -m 644 "$setup_dir/danted.conf" /etc/hosyu-wimax/danted.conf
install -m 644 "$setup_dir/hosyu-wimax-proxy.service" /etc/systemd/system/hosyu-wimax-proxy.service
install -m 755 "$setup_dir/90-hosyu-wimax" /etc/NetworkManager/dispatcher.d/90-hosyu-wimax
/usr/sbin/danted -V -f /etc/hosyu-wimax/danted.conf
systemctl daemon-reload
systemctl enable hosyu-wimax-proxy.service
systemctl restart hosyu-wimax-proxy.service
sleep 1
systemctl is-active --quiet hosyu-wimax-proxy.service

printf 'WiMAX connectivity check:\n'
if curl --silent --show-error --fail --noproxy '' \
    --proxy socks5h://127.0.0.1:10809 --connect-timeout 5 --max-time 12 \
    https://www.cloudflare.com/cdn-cgi/trace | grep '^ip='; then
    printf 'WiMAX is available for the posting browser.\n'
else
    printf 'WiMAX internet is unavailable; posting will use the normal connection.\n'
fi

# Same-directory rename avoids exposing a partially written script to cron.
install -m "$(stat -c %a "$tool_dir/hosyu_post.sh")" \
    -o "$(stat -c %u "$tool_dir/hosyu_post.sh")" \
    -g "$(stat -c %g "$tool_dir/hosyu_post.sh")" \
    "$setup_dir/hosyu_post.sh" "$tool_dir/.hosyu_post.wimax.$$"
install -m 644 /dev/null /etc/hosyu-wimax/enabled
mv -T -- "$tool_dir/.hosyu_post.wimax.$$" "$tool_dir/hosyu_post.sh"
printf 'WiMAX setup complete. Search uses Wan; posting prefers WiMAX with normal-line fallback.\n'
