#!/usr/bin/env bash
# aptly-release — aptly-pack + aptly-push in one call. The whole point of the
# deb-builder image: one command turns a source tree into a package on the
# repo, whichever of the four security presets is in effect.
#
# Usage: aptly-release [aptly-pack flags] -- [aptly-push flags]
# Anything before "--" goes to aptly-pack; anything after goes to aptly-push
# (files are appended automatically, do not pass them yourself).
#
# Example:
#   aptly-release --config nfpm.yaml -- --repo stable --distribution stable
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
log() { printf '[aptly-release] %s\n' "$*" >&2; }

pack_args=()
push_args=()
target=pack_args
for a in "$@"; do
  if [[ "$a" == "--" && "$target" == "pack_args" ]]; then
    target=push_args
    continue
  fi
  if [[ "$target" == "pack_args" ]]; then pack_args+=("$a"); else push_args+=("$a"); fi
done

log "packaging..."
mapfile -t debs < <("${SCRIPT_DIR}/aptly-pack" "${pack_args[@]}")
[[ "${#debs[@]}" -gt 0 ]] || { log "aptly-pack produced no output"; exit 1; }
for d in "${debs[@]}"; do log "  built: ${d}"; done

log "pushing..."
exec "${SCRIPT_DIR}/aptly-push" "${push_args[@]}" "${debs[@]}"
