#!/usr/bin/env bash
# Build an installable Arch package without installing host packages implicitly.
set -euo pipefail
[[ $# == 0 ]] || { printf 'Usage: tools/build-workstation\n' >&2; exit 2; }
(( EUID != 0 )) || { printf 'Build as an ordinary user\n' >&2; exit 2; }
cd "$(dirname -- "${BASH_SOURCE[0]}")/.."
for tool in makepkg pacman cargo rustc python3 git; do
    command -v "$tool" >/dev/null || { printf 'Missing %s; see docs/workstation.md\n' "$tool" >&2; exit 1; }
done
export FDS_SOURCE_DIR="$PWD"
mkdir -p out/workstation out/workstation-package
exec 9>out/.workstation-package.lock
flock -n 9 || { printf 'Another workstation package build is running\n' >&2; exit 1; }
cp packaging/arch/PKGBUILD out/workstation-package/PKGBUILD
export PKGDEST="$PWD/out/workstation"
cd out/workstation-package
# Dependencies are checked by their actual build commands. Runtime features
# are optional, and package installation is a separate explicit Make target.
makepkg --nodeps --force
mapfile -t packages < <(makepkg --packagelist)
(( ${#packages[@]} == 1 )) && [[ -s ${packages[0]} ]] || { printf 'Expected one fds-tools package\n' >&2; exit 1; }
printf '%s\n' "${packages[0]}" >../workstation/package-path.txt
printf 'Built Arch package: %s\nInstall with make workstation-install\n' "${packages[0]}"
