#!/bin/bash
set -euo pipefail

ROOT=$(cd "$(dirname "$0")/.." && pwd)
VERSION=${VERSION:-0.1.0}
RESTIC_VERSION=0.19.0
RESTIC_SHA256=13176fe6d89d4357947a2cd107218ab2873a5f9d8e1ac2d4cd1c8e07e6839c21
BUILD="$ROOT/build"
STAGE="$BUILD/package"
DIST="$ROOT/dist"

command -v go >/dev/null || { echo "Go 1.23 or newer is required" >&2; exit 1; }
command -v curl >/dev/null || { echo "curl is required" >&2; exit 1; }
command -v bzip2 >/dev/null || { echo "bzip2 is required" >&2; exit 1; }

rm -rf "$BUILD" "$DIST"
mkdir -p "$STAGE/usr/local/sbin" "$STAGE/usr/local/libexec/urbm" "$STAGE/usr/local/emhttp/plugins/urbm/assets" "$STAGE/usr/local/emhttp/plugins/urbm/images" "$STAGE/etc/rc.d" "$STAGE/install" "$DIST"

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w -X main.version=$VERSION" -o "$STAGE/usr/local/sbin/urbmd" ./cmd/urbmd

RESTIC_ARCHIVE="$BUILD/restic.bz2"
curl --fail --location --silent --show-error "https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}/restic_${RESTIC_VERSION}_linux_amd64.bz2" -o "$RESTIC_ARCHIVE"
read -r ACTUAL_RESTIC_SHA256 _ < <(sha256sum "$RESTIC_ARCHIVE")
if [ "$ACTUAL_RESTIC_SHA256" != "$RESTIC_SHA256" ]; then
  echo "Restic checksum mismatch" >&2
  exit 1
fi
bzip2 -dc "$RESTIC_ARCHIVE" > "$STAGE/usr/local/libexec/urbm/restic"
chmod 0755 "$STAGE/usr/local/libexec/urbm/restic" "$STAGE/usr/local/sbin/urbmd"

cp "$ROOT/webgui/URBM.page" "$STAGE/usr/local/emhttp/plugins/urbm/"
cp "$ROOT/webgui/api.php" "$STAGE/usr/local/emhttp/plugins/urbm/"
cp "$ROOT/webgui/assets/"* "$STAGE/usr/local/emhttp/plugins/urbm/assets/"
cp "$ROOT/webgui/images/"* "$STAGE/usr/local/emhttp/plugins/urbm/images/"
cp "$ROOT/webgui/assets/urbm.js" "$STAGE/usr/local/emhttp/plugins/urbm/assets/urbm-${VERSION}.js"
cp "$ROOT/plugin/rc.urbm" "$STAGE/etc/rc.d/rc.urbm"
cp "$ROOT/plugin/doinst.sh" "$ROOT/plugin/slack-desc" "$STAGE/install/"
chmod 0755 "$STAGE/etc/rc.d/rc.urbm" "$STAGE/install/doinst.sh"

(cd "$STAGE" && tar --owner=0 --group=0 -cJf "$DIST/urbm-${VERSION}-x86_64-1.txz" .)
(cd "$DIST" && sha256sum "urbm-${VERSION}-x86_64-1.txz" > "urbm-${VERSION}-x86_64-1.txz.sha256")
PACKAGE_SHA256=$(sha256sum "$DIST/urbm-${VERSION}-x86_64-1.txz" | awk '{print $1}')
sed "s/REPLACE_DURING_RELEASE/$PACKAGE_SHA256/" "$ROOT/plugin/urbm.plg" > "$DIST/urbm.plg"
echo "Built $DIST/urbm-${VERSION}-x86_64-1.txz"
