#!/bin/sh
# Demerzel agent installer.
#
#   curl -fsSL https://get.demerzel.cloud/install.sh | sh
#   curl -fsSL https://get.demerzel.cloud/install.sh | sh -s v0.1.0   # pin a version
#
# Env overrides: DEMERZEL_PREFIX (install dir, default /usr/local/bin),
# DEMERZEL_DOWNLOAD_BASE (default https://get.demerzel.cloud).
set -eu

BASE="${DEMERZEL_DOWNLOAD_BASE:-https://get.demerzel.cloud}"
VERSION="${1:-latest}"
PREFIX="${DEMERZEL_PREFIX:-/usr/local/bin}"
BIN="demerzel-agent"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
  linux | darwin) ;;
  *) echo "demerzel: unsupported OS '$os' (need linux or darwin)" >&2; exit 1 ;;
esac

arch=$(uname -m)
case "$arch" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *) echo "demerzel: unsupported architecture '$arch'" >&2; exit 1 ;;
esac

asset="demerzel-agent-${os}-${arch}"
url="${BASE}/${VERSION}/${asset}"

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

echo "demerzel: downloading ${url}"
curl -fsSL "$url" -o "$tmp/$BIN" || {
  echo "demerzel: download failed (is version '${VERSION}' published for ${os}/${arch}?)" >&2
  exit 1
}

# Verify the checksum when SHA256SUMS is available for this version.
if curl -fsSL "${BASE}/${VERSION}/SHA256SUMS" -o "$tmp/SHA256SUMS" 2>/dev/null; then
  expected=$(awk -v f="$asset" '$2 == f || $2 == "*"f {print $1}' "$tmp/SHA256SUMS" | head -1)
  if [ -n "$expected" ]; then
    if command -v sha256sum >/dev/null 2>&1; then
      actual=$(sha256sum "$tmp/$BIN" | awk '{print $1}')
    else
      actual=$(shasum -a 256 "$tmp/$BIN" | awk '{print $1}')
    fi
    if [ "$expected" != "$actual" ]; then
      echo "demerzel: checksum mismatch — refusing to install" >&2
      exit 1
    fi
    echo "demerzel: checksum verified"
  fi
fi

chmod +x "$tmp/$BIN"
dest="${PREFIX}/${BIN}"
# If the service setup relocated the binary (dest is a symlink into the
# service-owned dir, e.g. /opt/demerzel), write through to the real path so
# re-running the installer updates the binary the service actually runs, instead
# of replacing the symlink with a stale copy. Its directory stays service-owned,
# so auto-update keeps working regardless of who this write leaves it owned by.
if [ -L "$dest" ]; then
  dest="$(readlink -f "$dest")"
fi
destdir="$(dirname "$dest")"

if [ "$(id -u)" = 0 ] || [ -w "$destdir" ]; then
  mv "$tmp/$BIN" "$dest"
elif command -v sudo >/dev/null 2>&1; then
  echo "demerzel: installing into ${destdir} (sudo)"
  sudo mv "$tmp/$BIN" "$dest"
else
  echo "demerzel: ${destdir} is not writable and sudo is unavailable." >&2
  echo "demerzel: set DEMERZEL_PREFIX to a writable dir and re-run." >&2
  exit 1
fi

echo "demerzel: installed $("$dest" --version)"
echo "demerzel: next, enroll this host — see https://docs.demerzel.cloud/install-agent/enroll"
