#!/bin/bash

_help_message() {
    printf '\
Usage:

    generate-releases.sh VARIANTS

        - VARIANTS: A list of variants to generate (e.g., desktop).

    Optional variables:

        - ARCH: Tarball architecture (defaults to dpkg architecture).
        - BRANCH: Branch to use.
        - REPO: Repository mirror to use.
        - RETRO: Generate Retro releases (assign 1 to enable).
        - STAGE2: Stage2 mode (assign 1 to enable, uses $ARCH-bring-up branch).

'
}

if [[ $# -eq 0 || "$1" == "--help" || "$1" == "-h" ]]; then
	_help_message
	exit 0
fi

export TZ='UTC'

mkdir -pv os-${ARCH:-$(dpkg --print-architecture)}

for i in $@; do
	rm -r $i

	if [[ "$RETRO" != "1" ]]; then
		OS_NAME="aosc-os"
	else
		OS_NAME="afterglow"
	fi

	mkdir -pv os-${ARCH:-$(dpkg --print-architecture)}/${i/retro-/}

	if [[ "$i" != "wsl" ]]; then
		echo "Generating release ($i) ..."
		aoscbootstrap \
			--branch ${BRANCH:-stable} \
			--comps ${COMPS:-main} \
			--target $i \
			--mirror ${REPO:-https://repo.aosc.io/anthon/debs} \
			--config /usr/share/aoscbootstrap/config/aosc-mainline.toml \
			-x \
			--arch ${ARCH:-$(dpkg --print-architecture)} \
			-s \
				/usr/share/aoscbootstrap/scripts/reset-repo.sh \
			-s \
				/usr/share/aoscbootstrap/scripts/enable-nvidia-drivers.sh \
			-s \
				/usr/share/aoscbootstrap/scripts/enable-dkms.sh \
			-s \
				/usr/share/aoscbootstrap/scripts/desktop.sh \
			--include-files /usr/share/aoscbootstrap/recipes/$i.lst \
			--export-tar-xz os-${ARCH:-$(dpkg --print-architecture)}/${i/retro-/}/${OS_NAME}_${i/retro-/}_$(date +%Y%m%d)_${ARCH:-$(dpkg --print-architecture)}.tar.xz \
			--export-squashfs os-${ARCH:-$(dpkg --print-architecture)}/${i/retro-/}/${OS_NAME}_${i/retro-/}_$(date +%Y%m%d)_${ARCH:-$(dpkg --print-architecture)}.squashfs
	else
		echo "Generating WSL release ..."
		aoscbootstrap \
			--branch ${BRANCH:-stable} \
			--comps ${COMPS:-main} \
			--target $i \
			--mirror ${REPO:-https://repo.aosc.io/anthon/debs} \
			--config /usr/share/aoscbootstrap/config/aosc-mainline.toml \
			-x \
			--arch ${ARCH:-$(dpkg --print-architecture)} \
			-s \
				/usr/share/aoscbootstrap/scripts/reset-repo.sh \
			-s \
				/usr/share/aoscbootstrap/scripts/wsl-workarounds.sh \
			--include-files /usr/share/aoscbootstrap/recipes/$i.lst \
			--export-tar-gz os-${ARCH:-$(dpkg --print-architecture)}/$i/${OS_NAME}_${i}_$(date +%Y%m%d)_${ARCH:-$(dpkg --print-architecture)}.wsl
	fi
	rm -r $i

	# Hack, just to make sure that things are catching up (we observed a weird caching issue on kp920).
	sync
	sleep 1
done
