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

usage() {
	echo "Usage: $0 --target <TARGET> --subtarget <SUBTARGET> --profile <PROFILE> --server-ipv4 <ADDR> --server-port <PORT> --uuid <UUID> [OCG_ARGS]"
	exit 1
}

# Parse arguments.
while [ $# -gt 0 ]; do
	case "$1" in
	--target)
		[ -z "$2" ] && usage
		target="$2"
		shift 2
		;;
	--subtarget)
		[ -z "$2" ] && usage
		subtarget="$2"
		shift 2
		;;
	--profile)
		[ -z "$2" ] && usage
		profile="$2"
		shift 2
		;;
	--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
		;;
	*)
		OCG_ARGS="${OCG_ARGS:+$OCG_ARGS }$1"
		shift
		;;
	esac
done

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

# Download imagebuilder if its directory doesn't exist.
if [ ! -d "openwrt-imagebuilder-24.10.5-$TARGET-$SUBTARGET.Linux-x86_64" ]; then
	curl -O "https://downloads.openwrt.org/releases/24.10.5/targets/$TARGET/$SUBTARGET/openwrt-imagebuilder-24.10.5-$TARGET-$SUBTARGET.Linux-x86_64.tar.zst"
	tar xf "openwrt-imagebuilder-24.10.5-$TARGET-$SUBTARGET.Linux-x86_64.tar.zst"
fi

# Clone bsbf-client-openwrt-config-generator.
git clone https://github.com/bondingshouldbefree/bsbf-client-openwrt-config-generator
cd bsbf-client-openwrt-config-generator

# Generate BSBF bonding configuration and install it.
PACKAGES=$(./bsbf-client-openwrt-config-generator.sh --server-ipv4 "$server_ipv4" --server-port "$server_port" --uuid "$uuid" $OCG_ARGS)
install -D 99-bsbf-bonding-2 ../openwrt-imagebuilder-24.10.5-$TARGET-$SUBTARGET.Linux-x86_64/files/etc/uci-defaults/99-bsbf-bonding-2

# Remove bsbf-client-openwrt-config-generator.
cd ..
rm -rf bsbf-client-openwrt-config-generator

# Generate an image.
cd openwrt-imagebuilder-24.10.5-$TARGET-$SUBTARGET.Linux-x86_64
make image \
PROFILE="$PROFILE" \
PACKAGES="$PACKAGES" \
FILES="files"
