#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2026 Chester A. Unal <chester.a.unal@arinc9.com>

usage() {
	echo "Usage: $0 --server-ipv4 <ADDR> --server-port <PORT> --uuid <UUID> | --uninstall"
	exit 1
}

# Parse arguments.
while [ $# -gt 0 ]; do
	case "$1" in
	--uninstall)
		apk del bsbf-bonding
		uci set xray.enabled.enabled='0'
		uci commit
		service xray reload
		service firewall reload
		exit
		;;
	--server-ipv4)
		[ -z "$2" ] && usage
		server_ipv4="$2"
		shift 2
		;;
	--server-port)
		[ -z "$2" ] && usage
		server_port="$2"
		shift 2
		;;
	--uuid)
		[ -z "$2" ] && usage
		uuid="$2"
		shift 2
		;;
	*)
		usage
		;;
	esac
done

# Show usage if server IPv4 address, server port, and UUID were not provided.
{ [ -z "$server_ipv4" ] || [ -z "$server_port" ] || [ -z "$uuid" ]; } && usage

BSBF_RESOURCES="https://raw.githubusercontent.com/bondingshouldbefree/bsbf-resources/refs/heads/main"

# Install bsbf-bonding, jq, kmod-sched, kmod-sched-bpf, and kmod-nft-tproxy.
apk add bsbf-bonding jq kmod-sched kmod-sched-bpf kmod-nft-tproxy

# xray Configuration
curl -s $BSBF_RESOURCES/resources-client/xray.json \
  | jq --arg SERVER "$server_ipv4" \
       --argjson PORT "$server_port" \
       --arg UUID "$uuid" '
        .outbounds[0].settings.address = $SERVER
      | .outbounds[0].settings.port = $PORT
      | .outbounds[0].settings.id = $UUID' \
  > /etc/xray/config.json

# bsbf-plpmtu Configuration
curl -s $BSBF_RESOURCES/resources-shared/bsbf-plpmtu \
  | sed "s/^\(PLPMTUD_NODE=\"\)[^:]*/\1$server_ipv4/" \
  > /usr/sbin/bsbf-plpmtu

chmod +x /usr/sbin/bsbf-plpmtu

# bsbf-tcp-in-udp Configuration
curl -s $BSBF_RESOURCES/resources-client/bsbf-tcp-in-udp \
  | sed -e "s/^PORT=.*/PORT=$server_port/" \
	-e "s/^IPv4=.*/IPv4=\"$server_ipv4\"/" \
  > /usr/sbin/bsbf-tcp-in-udp

chmod +x /usr/sbin/bsbf-tcp-in-udp

echo "Installation complete. Plug in to $(uci get network.lan.device) to access LAN."

# Reload services.
service xray reload &
service firewall reload &
service network reload &
