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

if [ "$#" -ne 1 ]; then
  echo "Usage: stage-release VERSION" >&2
  exit 2
fi
if [ "$(id -u)" -ne 0 ]; then
  echo "Release staging must run as root." >&2
  exit 1
fi

version="$1"
package_root="/usr/lib/nucleus-server/package"
release_root="/opt/nucleus/releases"
target="$release_root/$version"

if ! printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$|^dev$|^0\.0\.0~dev$|^0\.0\.0-dev$'; then
  echo "Invalid staged Nucleus version." >&2
  exit 1
fi
for binary in nucleus-server numin; do
  if [ ! -x "$package_root/$binary" ]; then
    echo "The package payload is incomplete: $binary is missing." >&2
    exit 1
  fi
done

getent group nucleus >/dev/null 2>&1 || groupadd --system nucleus
if ! getent passwd nucleus >/dev/null 2>&1; then
  useradd \
    --system \
    --gid nucleus \
    --home-dir /var/lib/nucleus \
    --shell /usr/sbin/nologin \
    nucleus
fi

install -d -o root -g root -m 0755 /etc/nucleus
install -d -o nucleus -g nucleus -m 0750 /var/lib/nucleus
install -d -o root -g root -m 0755 /opt/nucleus
install -d -o root -g root -m 0755 "$release_root"
install -d -o nucleus -g nucleus -m 0750 \
  /var/lib/nucleus/runtime \
  /var/lib/nucleus/storage \
  /var/lib/nucleus/tmp \
  /var/lib/nucleus/backups

if [ -d "$target" ]; then
  for binary in nucleus-server numin; do
    if ! cmp -s "$package_root/$binary" "$target/$binary"; then
      echo "The immutable release directory already exists with different content." >&2
      exit 1
    fi
  done
else
  temporary="$release_root/.${version}.new.$$"
  trap 'rm -rf "$temporary"' EXIT
  install -d -o root -g root -m 0755 "$temporary"
  install -o root -g root -m 0755 "$package_root/nucleus-server" "$temporary/nucleus-server"
  install -o root -g root -m 0755 "$package_root/numin" "$temporary/numin"
  printf '%s\n' "$version" > "$temporary/VERSION"
  chmod 0644 "$temporary/VERSION"
  mv "$temporary" "$target"
  trap - EXIT
fi

if [ ! -L "$release_root/current" ]; then
  temporary_link="$release_root/.current.new.$$"
  ln -s "$target" "$temporary_link"
  mv -T "$temporary_link" "$release_root/current"
  echo "Staged and selected first Nucleus release $version; the service remains stopped."
else
  echo "Staged Nucleus release $version; the active release was not changed."
fi
