#!/usr/bin/env bash
# aptly-pack — build a .deb without requiring Debian packaging knowledge.
#
# Two modes, auto-detected:
#   1. A debian/ directory exists in --source-dir -> delegate to the real
#      Debian toolchain: `dpkg-buildpackage -us -uc -b` (binary-only, unsigned;
#      signing is aptly's job at publish time, not the package's).
#   2. Otherwise -> nfpm (https://nfpm.goreleaser.com/), driven by a plain
#      nfpm.yaml describing name/version/files — no debian/ dir needed.
#
# Only runs inside the aptly-deb-builder image, which has both toolchains.
#
# Usage:
#   aptly-pack [--source-dir .] [--config nfpm.yaml] [--output-dir dist]
#
# For the nfpm path, target architecture is whatever `arch:` says in the
# nfpm.yaml itself (nfpm has no --arch flag — a config describes one arch;
# for multi-arch packages, run aptly-pack once per arch-specific config).
#
# Prints the path(s) of the produced .deb file(s) on stdout, one per line —
# meant to be fed straight into aptly-push:
#   aptly-push --repo stable $(aptly-pack)
set -euo pipefail

log() { printf '[aptly-pack] %s\n' "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }

SOURCE_DIR="."
CONFIG="nfpm.yaml"
OUTPUT_DIR="dist"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --source-dir) SOURCE_DIR="$2"; shift 2 ;;
    --config) CONFIG="$2"; shift 2 ;;
    --output-dir) OUTPUT_DIR="$2"; shift 2 ;;
    *) die "unknown argument: $1" ;;
  esac
done

mkdir -p "$OUTPUT_DIR"
OUTPUT_DIR="$(cd -- "$OUTPUT_DIR" && pwd)"

if [[ -d "${SOURCE_DIR}/debian" ]]; then
  log "found ${SOURCE_DIR}/debian -> building with dpkg-buildpackage"
  command -v dpkg-buildpackage >/dev/null 2>&1 || die "dpkg-buildpackage not found (wrong image?)"
  (
    cd "$SOURCE_DIR"
    dpkg-buildpackage -us -uc -b
  )
  # dpkg-buildpackage drops artifacts one level above the source tree.
  parent_dir="$(cd -- "${SOURCE_DIR}/.." && pwd)"
  found=0
  for f in "${parent_dir}"/*.deb; do
    [[ -e "$f" ]] || continue
    mv -- "$f" "$OUTPUT_DIR/"
    printf '%s\n' "${OUTPUT_DIR}/$(basename -- "$f")"
    found=1
  done
  [[ "$found" -eq 1 ]] || die "dpkg-buildpackage produced no .deb file"
else
  cfg="${SOURCE_DIR}/${CONFIG}"
  [[ -f "$cfg" ]] || die "no ${SOURCE_DIR}/debian and no nfpm config at ${cfg} — nothing to build"
  command -v nfpm >/dev/null 2>&1 || die "nfpm not found (wrong image?)"
  log "packaging with nfpm (config: ${cfg})"
  (
    cd "$SOURCE_DIR"
    nfpm package --config "$(basename -- "$cfg")" --target "$OUTPUT_DIR" --packager deb
  )
  found=0
  for f in "${OUTPUT_DIR}"/*.deb; do
    [[ -e "$f" ]] || continue
    printf '%s\n' "$f"
    found=1
  done
  [[ "$found" -eq 1 ]] || die "nfpm produced no .deb file"
fi
