#!/bin/sh
# Afaron for Linux (and Linux inside Windows: WSL) — https://afaron.com
#
#   curl -fsSL https://afaron.com/install.sh | sh
#
# Puts Afaron in ~/.local/share/afaron and the `afaron` command in ~/.local/bin: nothing outside
# your home folder, no root. Then `afaron setup` starts it, signs this computer in to your Afaron
# account (you open a link on your phone), and pairs your phone.
#
# AFARON_PACKAGE=/path/to/afaron-<version>-linux-<arch>.tar.gz installs a package you already have.
set -eu

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

[ "$(id -u)" != 0 ] || die "run this as yourself, not as root: Afaron runs as your own user."
[ "$(uname -s)" = Linux ] || die "this installer is for Linux. On a Mac, get Afaron at https://afaron.com/download"
case "$(uname -m)" in
  x86_64 | amd64) arch=x64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *) die "this processor ($(uname -m)) is not supported yet: x86-64 and ARM64 are." ;;
esac
# The package's Node.js needs glibc 2.28 or newer (Debian 10, Ubuntu 20.04, RHEL 8, Fedora 29 and later).
glibc=$(getconf GNU_LIBC_VERSION 2>/dev/null | sed -n 's/^glibc //p')
[ -n "$glibc" ] || die "this system has no glibc (Alpine and other musl systems are not supported yet)."
major=${glibc%%.*}; minor=${glibc#*.}; minor=${minor%%.*}
[ "$major" -gt 2 ] || [ "$minor" -ge 28 ] || die "glibc $glibc is too old: 2.28 or newer is needed."
for tool in tar gzip sha256sum; do command -v "$tool" >/dev/null 2>&1 || die "$tool is needed and not installed."; done

base="${XDG_DATA_HOME:-$HOME/.local/share}/afaron"
mkdir -p "$base/versions" "$HOME/.local/bin"
work=$(mktemp -d "$base/.install.XXXXXX")
trap 'rm -rf "$work"' EXIT INT TERM

if [ -n "${AFARON_PACKAGE:-}" ]; then
  [ -f "$AFARON_PACKAGE" ] || die "there is no package at $AFARON_PACKAGE"
  cp "$AFARON_PACKAGE" "$work/afaron.tar.gz"
else
  command -v curl >/dev/null 2>&1 || die "curl is needed and not installed."
  # The newest release for this processor: its version, a download link and the archive's SHA-256.
  release=$(curl -fsSL "${AFARON_RELEASES:-https://relay.wenqian.dev/v1/linux/latest}?arch=$arch") || die "the release could not be looked up. Try again in a moment."
  field() { printf '%s' "$release" | tr -d '\n' | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p"; }
  number() { printf '%s' "$release" | tr -d '\n' | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p"; }
  version=$(field version); url=$(field url); sum=$(field sha256); size=$(number size); signature=$(field signature)
  printf '%s' "$version" | grep -Eq '^[0-9]+(\.[0-9]+){2,3}$' || die "the release service gave an answer this installer does not understand."
  printf '%s' "$sum" | grep -Eq '^[0-9a-f]{64}$' && [ -n "$url" ] && [ -n "$size" ] || die "the release service gave an answer this installer does not understand."
  case "$url" in https://*) ;; *) [ -n "${AFARON_RELEASES:-}" ] || die "the download link is not https." ;; esac
  say "Downloading Afaron $version for Linux ($arch)…"
  curl -fL --progress-bar -o "$work/afaron.tar.gz" "$url" || die "the download did not finish. Try again."
  got=$(sha256sum "$work/afaron.tar.gz" | cut -d' ' -f1)
  [ "$got" = "$sum" ] || die "the download is damaged (its checksum does not match). Nothing was installed."
  # The release key's signature over version, processor, checksum and size: checked where OpenSSL can (3.0 and
  # later). The installed command checks it for every update.
  if command -v openssl >/dev/null 2>&1 && openssl pkeyutl -help 2>&1 | grep -q rawin; then
    printf '%s\n' '-----BEGIN PUBLIC KEY-----' 'MCowBQYDK2VwAyEAm/VIdde00jwLmoG+WZHRC26GjiJJmk9owx6iFKaEbfo=' '-----END PUBLIC KEY-----' > "$work/release.pem"
    printf 'afaron-linux\n%s\n%s\n%s\n%s' "$version" "$arch" "$sum" "$size" > "$work/release.msg"
    printf '%s' "$signature" | base64 -d > "$work/release.sig" 2>/dev/null || die "the release is not signed. Nothing was installed."
    openssl pkeyutl -verify -pubin -inkey "$work/release.pem" -rawin -in "$work/release.msg" -sigfile "$work/release.sig" >/dev/null 2>&1 ||
      die "the package is not signed with Afaron's release key. Nothing was installed."
  else
    say "(This system's OpenSSL cannot check the release signature; the package's checksum was checked.)"
  fi
fi

mkdir "$work/unpacked"
tar -xzf "$work/afaron.tar.gz" -C "$work/unpacked" || die "the package could not be unpacked."
top=$(ls "$work/unpacked")
# One folder, afaron-<version>, and nothing else.
case "$top" in afaron-[0-9]*) ;; *) die "this is not an Afaron package." ;; esac
[ "$(ls "$work/unpacked" | wc -l)" -eq 1 ] || die "this is not an Afaron package."
[ -x "$work/unpacked/$top/bin/afaron" ] || die "this is not an Afaron package."
got_version=$("$work/unpacked/$top/bin/afaron" --version 2>"$work/run.err") || {
  # A library the system lacks (a minimal system may have no libatomic, which Node.js needs): said by name.
  missing=$(ldd "$work/unpacked/$top/runtime/node" 2>/dev/null | sed -n 's/^[[:space:]]*\([^[:space:]]*\) => not found.*/\1/p' | tr '\n' ' ')
  case "$missing" in
    *libatomic*) die "Afaron needs the library libatomic, which is not installed: sudo apt install libatomic1 (Debian, Ubuntu) or sudo dnf install libatomic (Fedora, RHEL), then run this again." ;;
  esac
  [ -z "$missing" ] || die "the package needs libraries this system does not have: $missing"
  die "the package does not run on this system: $(head -c 300 "$work/run.err")"
}
printf '%s' "$got_version" | grep -Eq '^[0-9]+(\.[0-9]+){2,3}$' || die "this is not an Afaron package."
[ -z "${version:-}" ] || [ "$got_version" = "$version" ] || die "the package says it is $got_version, not $version."
rm -rf "$base/versions/$got_version"
mv "$work/unpacked/$top" "$base/versions/$got_version"
ln -sfn "versions/$got_version" "$base/current.new" && mv -T "$base/current.new" "$base/current"
ln -sfn "$base/current/bin/afaron" "$HOME/.local/bin/afaron"
say "Afaron $got_version is installed in $base."

case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) say "(~/.local/bin is not on your PATH yet: open a new terminal, or run: export PATH=\"\$HOME/.local/bin:\$PATH\")" ;; esac

# The setup asks questions: from the terminal, also when this script came through a pipe.
if [ -z "${AFARON_NO_SETUP:-}" ]; then
  if [ -r /dev/tty ] && [ -w /dev/tty ] && (: </dev/tty) 2>/dev/null; then
    exec "$base/current/bin/afaron" setup </dev/tty
  fi
  exec "$base/current/bin/afaron" setup
fi
