#!/bin/sh
# Installs acf, the Forge CLI, from https://forge.anyonecan.software
#
#   curl -fsSL https://forge.anyonecan.software/install.sh | sh
#
# It downloads the build for this computer, checks it against the forge's
# published SHA-256 checksums, and puts it in ~/.local/bin (or
# $ACF_INSTALL_DIR). Nothing else is changed unless you're already signed in
# to a forge, in which case git's sign-in helper is pointed at the new acf.
set -eu

FORGE="https://forge.anyonecan.software"
DIR="${ACF_INSTALL_DIR:-$HOME/.local/bin}"

say()  { printf '%s\n' "$*"; }
fail() { printf 'acf install: %s\n' "$*" >&2; exit 1; }

case "$(uname -s)" in
  Linux)  os=linux ;;
  Darwin) os=darwin ;;
  *) fail "this installer is for macOS and Linux. On Windows, download acf from $FORGE/install" ;;
esac
case "$(uname -m)" in
  x86_64 | amd64)  arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) fail "there's no build for $(uname -m) yet; you can build it from source with Go" ;;
esac

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -q "$1" -O "$2"; }
else
  fail "please install curl or wget first"
fi
if command -v sha256sum >/dev/null 2>&1; then
  sha256() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null 2>&1; then
  sha256() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
  fail "please install sha256sum (or shasum) so the download can be checked"
fi

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

fetch "$FORGE/downloads/acf/versions" "$tmp/versions" || fail "couldn't reach $FORGE"
version="$(sed -n 's/.*"latest": *"\([0-9.]*\)".*/\1/p' "$tmp/versions")"
[ -n "$version" ] || fail "$FORGE hasn't published the CLI yet"

file="acf-$os-$arch"
say "☁ Downloading acf $version for $os/$arch from $FORGE…"
fetch "$FORGE/downloads/acf/$version/$file.gz" "$tmp/acf.gz" || fail "download failed"
fetch "$FORGE/downloads/acf/$version/SHA256SUMS" "$tmp/SHA256SUMS" || fail "couldn't get the checksums"
gunzip "$tmp/acf.gz"
want="$(grep "  $file\$" "$tmp/SHA256SUMS" | cut -d' ' -f1)"
got="$(sha256 "$tmp/acf")"
[ -n "$want" ] && [ "$want" = "$got" ] || fail "the download doesn't match its published checksum, so it wasn't installed"

mkdir -p "$DIR"
chmod 755 "$tmp/acf"
mv "$tmp/acf" "$DIR/acf"
say "✓ Installed acf $version at $DIR/acf (checksum verified)"

case ":$PATH:" in
  *":$DIR:"*) ;;
  *) say ""
     say "  $DIR isn't on your PATH yet. Add this to your shell's profile:"
     say "    export PATH=\"$DIR:\$PATH\"" ;;
esac

say ""
if "$DIR/acf" whoami >/dev/null 2>&1 </dev/null; then
  # Already signed in: point git's sign-in helper at this acf.
  "$DIR/acf" setup-git </dev/null || true
else
  say "  Next, sign in and let git use it:"
  say "    acf login --url $FORGE"
  say "    acf setup-git"
fi
