#!/usr/bin/env bash
set -euo pipefail

version="$(bun --eval "console.log(JSON.parse(await Bun.file('package.json').text()).version)")"
arch="x64"
output_dir="app_dist"
binary="${output_dir}/linux/farmcontrol-server"
pdfjs_data="${output_dir}/linux/pdfjs-data"
deb_name="farmcontrol-server-${version}-${arch}.deb"
rpm_name="farmcontrol-server-${version}-${arch}.rpm"

common_fpm_args=(
  -f
  -s dir
  -n farmcontrol-server
  -p "${output_dir}/"
  -v "${version}"
  --after-install packaging/linux/after-install.sh
  --before-remove packaging/linux/before-remove.sh
  --after-remove packaging/linux/after-remove.sh
  "${binary}=/usr/bin/farmcontrol-server"
  "${pdfjs_data}=/usr/lib/farmcontrol-server/pdfjs-data"
  packaging/linux/farmcontrol-server.service=/lib/systemd/system/farmcontrol-server.service
)

fpm -t deb "${common_fpm_args[@]}"
fpm -t rpm "${common_fpm_args[@]}"

deb_source="${output_dir}/farmcontrol-server_${version}_amd64.deb"
rpm_source="${output_dir}/farmcontrol-server-${version}-1.x86_64.rpm"

if [[ ! -f "${deb_source}" ]]; then
  deb_source="$(find "${output_dir}" -maxdepth 1 -name 'farmcontrol-server_*_amd64.deb' | head -n 1)"
fi

if [[ ! -f "${rpm_source}" ]]; then
  rpm_source="$(find "${output_dir}" -maxdepth 1 -name 'farmcontrol-server-*.x86_64.rpm' | head -n 1)"
fi

if [[ -z "${deb_source}" || ! -f "${deb_source}" ]]; then
  echo "Could not find generated .deb package in ${output_dir}" >&2
  exit 1
fi

if [[ -z "${rpm_source}" || ! -f "${rpm_source}" ]]; then
  echo "Could not find generated .rpm package in ${output_dir}" >&2
  exit 1
fi

mv "${deb_source}" "${output_dir}/${deb_name}"
mv "${rpm_source}" "${output_dir}/${rpm_name}"

rm -rf "${output_dir}/linux"

echo "Published ${output_dir}/${deb_name}"
echo "Published ${output_dir}/${rpm_name}"
