#!/bin/sh
# Swarmfile server (`swarmfile-server`) installer.
#
#   curl -fsSL https://get.swarmfile.com/server | sh
#
# Downloads the release asset for this OS/arch from the public release of the
# Swarmfile repository `swarmfile/swarmfile-server`, verifies its SHA-256 against
# the `.sha256` asset published next to it, and installs the
# `swarmfile-server` binary. POSIX sh, no bashisms.
#
# Environment (all optional):
#   SWARMFILE_SERVER_BINDIR    install directory (default: ~/.local/bin when
#                              writable, else /usr/local/bin when writable —
#                              this script never calls sudo)
#   SWARMFILE_SERVER_VERSION   pin a version, e.g. 0.3.10 (or server-v0.3.10);
#                              default: newest `server-v*` release
#   SWARMFILE_SERVER_HUB_URL   hub base for the public repository
#                              (default: https://hub.swarmfile.com)
#   SWARMFILE_SERVER_ORG       public-repository org slug (default: swarmfile)
#   SWARMFILE_SERVER_PROJECT   public-repository slug (default: swarmfile-server)
#   SWARMFILE_SERVER_ASSETS_BASE / SWARMFILE_SERVER_RELEASES_URL
#                              override the asset / release-list URLs
#   SWARMFILE_SERVER_ALLOW_UNVERIFIED=1
#                              install even when no .sha256 asset exists;
#                              the default is to REFUSE rather than install
#                              bytes nobody vouched for
#
# Exit codes: 0 installed · 1 failure (unsupported platform, download,
# checksum mismatch, no writable install dir, …).

set -eu

VERSION="${SWARMFILE_SERVER_VERSION:-}"
ORG="${SWARMFILE_SERVER_ORG:-swarmfile}"
PROJECT="${SWARMFILE_SERVER_PROJECT:-swarmfile-server}"
HUB="${SWARMFILE_SERVER_HUB_URL:-https://hub.swarmfile.com}"
ASSETS_BASE="${SWARMFILE_SERVER_ASSETS_BASE:-${HUB}/public/${ORG}/${PROJECT}/assets}"
RELEASES_URL="${SWARMFILE_SERVER_RELEASES_URL:-${HUB}/public/${ORG}/${PROJECT}/releases}"

say()  { printf '%s\n' "$*"; }
warn() { printf 'warning: %s\n' "$*" >&2; }
die()  { printf 'error: %s\n' "$*" >&2; exit 1; }

HAS=""
for c in curl wget; do
  if command -v "$c" >/dev/null 2>&1; then HAS="$c"; break; fi
done
[ -n "$HAS" ] || die "need curl or wget to download the server"

fetch() { # fetch <url>
  if [ "$HAS" = "curl" ]; then curl -fsSL "$1"; else wget -q -O - "$1"; fi
}
fetch_to() { # fetch_to <url> <path>
  if [ "$HAS" = "curl" ]; then curl -fsSL -o "$2" "$1"; else wget -q -O "$2" "$1"; fi
}
sha256_of() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    die "need shasum or sha256sum to verify the download"
  fi
}

latest_version() {
  BODY="$(fetch "$RELEASES_URL" 2>/dev/null)" || return 1
  printf '%s' "$BODY" \
    | tr ',' '\n' \
    | sed -n 's/.*"tagName"[[:space:]]*:[[:space:]]*"server-v\([^"]*\)".*/\1/p' \
    | head -n 1
}

OS_RAW="$(uname -s 2>/dev/null || echo unknown)"
ARCH_RAW="$(uname -m 2>/dev/null || echo unknown)"

case "$OS_RAW" in
  Darwin) OS=macos ;;
  Linux)  OS=linux ;;
  MINGW*|MSYS*|CYGWIN*|Windows_NT)
    # Windows: the release ships a .zip and there is no PATH installer for
    # this POSIX script; point at the zip (the container image or a source
    # build are the alternatives).
    cat <<PWSEOF
Windows detected — this script only installs on macOS and Linux. Download the
release zip instead:

  swarmfile-server-<version>-windows-x64.zip

from the public release page, unzip it, and run swarmfile-server.exe.
Releases: https://swarmfile.com
PWSEOF
    exit 1
    ;;
  *)
    die "unsupported OS '$OS_RAW' (macOS, Linux, and Windows are supported)"
    ;;
esac

case "$ARCH_RAW" in
  arm64|aarch64) ARCH=arm64 ;;
  x86_64|amd64)  ARCH=x64 ;;
  *) die "unsupported architecture '$ARCH_RAW' (arm64 and x86_64 are supported)" ;;
esac

ASSET="${OS}-${ARCH}"

case "$VERSION" in
  server-v*) VERSION="${VERSION#server-v}" ;;
esac
if [ -z "$VERSION" ]; then
  say "resolving the latest swarmfile-server release…"
  VERSION="$(latest_version || true)"
  [ -n "$VERSION" ] || die "could not resolve the latest server-v* release — set SWARMFILE_SERVER_VERSION to pin one"
fi
TAG="server-v${VERSION}"

if [ -n "${SWARMFILE_SERVER_BINDIR:-}" ]; then
  BINDIR="$SWARMFILE_SERVER_BINDIR"
  mkdir -p "$BINDIR" 2>/dev/null || true
  [ -d "$BINDIR" ] && [ -w "$BINDIR" ] || die "SWARMFILE_SERVER_BINDIR=$BINDIR is not a writable directory"
elif mkdir -p "$HOME/.local/bin" 2>/dev/null && [ -w "$HOME/.local/bin" ]; then
  BINDIR="$HOME/.local/bin"
elif [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
  BINDIR=/usr/local/bin
else
  die "no writable install directory (tried \$SWARMFILE_SERVER_BINDIR, $HOME/.local/bin, /usr/local/bin).
       Re-run with an explicit directory:
         curl -fsSL https://get.swarmfile.com/server | SWARMFILE_SERVER_BINDIR=\"\$HOME/.local/bin\" sh"
fi

NAME="swarmfile-server-${VERSION}-${ASSET}"
URL="${ASSETS_BASE}/${NAME}.tar.gz?tag=${TAG}"
SHA_URL="${ASSETS_BASE}/${NAME}.tar.gz.sha256?tag=${TAG}"
TMP="$(mktemp -d "${TMPDIR:-/tmp}/swarmfile-server.XXXXXX")" || die "could not create a temp directory"
# shellcheck disable=SC2064
trap 'rm -rf "$TMP"' EXIT HUP INT TERM

say "downloading $NAME ($TAG)…"
fetch_to "$URL" "$TMP/server.tar.gz" \
  || die "download failed: $URL (pin SWARMFILE_SERVER_VERSION if the latest release is mid-publish)"

say "verifying SHA-256…"
EXPECTED=""
if fetch_to "$SHA_URL" "$TMP/server.tar.gz.sha256" 2>/dev/null; then
  EXPECTED="$(tr -d '\r' < "$TMP/server.tar.gz.sha256" | awk '{print $1}' | head -n 1)"
fi
if [ -n "$EXPECTED" ]; then
  ACTUAL="$(sha256_of "$TMP/server.tar.gz")"
  [ "$EXPECTED" = "$ACTUAL" ] || die "checksum mismatch!
       expected $EXPECTED
       actual   $ACTUAL
       Refusing to install."
elif [ "${SWARMFILE_SERVER_ALLOW_UNVERIFIED:-0}" = "1" ]; then
  warn "no .sha256 asset published for $NAME — proceeding unverified (SWARMFILE_SERVER_ALLOW_UNVERIFIED=1)"
else
  die "no .sha256 asset published for $NAME — refusing to install unverified."
fi

tar -xzf "$TMP/server.tar.gz" -C "$TMP" || die "could not extract the archive"
[ -f "$TMP/swarmfile-server" ] || die "archive did not contain the swarmfile-server binary"
chmod 0755 "$TMP/swarmfile-server"

DEST="$BINDIR/swarmfile-server"
STAGED="$BINDIR/.swarmfile-server.new.$$"
cp "$TMP/swarmfile-server" "$STAGED" && chmod 0755 "$STAGED" && mv -f "$STAGED" "$DEST" || {
  rm -f "$STAGED"
  die "could not install to $DEST"
}

say "installed: $DEST"
say ""
say "Next steps:"
say "  1. Initialize a data directory and mint a key:"
say "       $DEST admin --data-dir ./swarmfile-data init"
say "       $DEST admin --data-dir ./swarmfile-data create-org --id my-org --name 'My Org'"
say "       $DEST admin --data-dir ./swarmfile-data create-repository --org my-org --name 'My Repository'"
say "       $DEST admin --data-dir ./swarmfile-data mint-key --org my-org --repository <repository-id> --name cli"
say "  2. Serve it (TLS via a reverse proxy):"
say "       $DEST serve --data-dir ./swarmfile-data --listen 127.0.0.1:8080"
say "  3. Point git-lfs at $HUB/orgs/my-org/lfs/<repository-id> and clone with"
say "     git-remote-swarmfile. Docs: https://swarmfile.com"
