#!/bin/sh
# Installs Hop after checking that the download is the one you expect.
#
#   HOP_DOWNLOAD_BASE=<url> ./install.sh <version> <sha256 of the zip>
#   HOP_DOWNLOAD_BASE=<url> ./install.sh --release <RELEASE.json file or URL>
#   ./install.sh --from-source <git url> <full commit id>
#
# HOP_DOWNLOAD_BASE is the folder the zip is served from (https://, http:// or file://).
# The zip is installed only if its sha256 matches. Take the expected sha256 (or the RELEASE.json)
# from a place you trust: a checksum served next to the zip only proves the download was not damaged.
# --from-source clones the code, checks out exactly that commit, builds it on this Mac and installs it.
#
# Hop needs the macOS version named in the app (26 or later). On an older system nothing is installed.
#
# Options through the environment:
#   HOP_INSTALL_DIR  where Hop.app goes (default: ~/Applications)
#   HOP_NO_OPEN=1    do not open Hop after installing (also lets the install go ahead while a Hop from
#                    another folder is running; that one is left alone)
#   HOP_NO_CLI=1     do not put the hop command in ~/.local/bin (it is also left out when
#                    HOP_INSTALL_DIR is set: a Hop in a folder of your choosing does not take the name)
set -eu

say() { printf '%s\n' "$*"; }
die() { printf 'install.sh: %s\n' "$*" >&2; exit 1; }
usage() { sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
BUNDLE_ID=com.aienos.hop
sha() { shasum -a 256 "$1" | cut -d' ' -f1; }
is_sha() { printf '%s' "$1" | grep -Eq '^[0-9a-f]{64}$'; }

[ "$(uname -s)" = "Darwin" ] || die "Hop runs on macOS only"
[ "$(uname -m)" = "arm64" ] || die "Hop needs an Apple silicon Mac"

DEST_DIR=${HOP_INSTALL_DIR:-$HOME/Applications}
DEST="$DEST_DIR/Hop.app"
WORK=$(mktemp -d "${TMPDIR:-/tmp}/hop-install.XXXXXX")
trap 'rm -rf "$WORK"' EXIT

# Stops, before anything is downloaded, built or moved, when this Mac's macOS is older than the app needs.
# HOP_TEST_MACOS_VERSION stands in for the detected version (tests only).
need_macos() {   # need_macos <minimum version, e.g. 26.0>
  MIN_MAJOR=${1%%.*}
  HAVE=${HOP_TEST_MACOS_VERSION:-$(sw_vers -productVersion)}
  HAVE_MAJOR=${HAVE%%.*}
  printf '%s' "$MIN_MAJOR" | grep -Eq '^[0-9]+$' || die "cannot read the macOS version Hop needs ($1); nothing was installed"
  printf '%s' "$HAVE_MAJOR" | grep -Eq '^[0-9]+$' || die "cannot read this Mac's macOS version ($HAVE); nothing was installed"
  [ "$HAVE_MAJOR" -ge "$MIN_MAJOR" ] || die "this Mac runs macOS $HAVE, and Hop needs macOS $MIN_MAJOR or later; nothing was installed"
}
plist_min() { /usr/libexec/PlistBuddy -c 'Print :LSMinimumSystemVersion' "$1" 2>/dev/null || die "cannot read the macOS version Hop needs from $1; nothing was installed"; }

fetch() {   # fetch <url> <file>
  curl --fail --silent --show-error --location --proto '=https,http,file' -o "$2" "$1" || die "could not download $1"
}

# Puts a checked Hop.app in place. The app that was there is kept as a backup.
install_app() {   # install_app <path to Hop.app>
  [ -x "$1/Contents/MacOS/Hop" ] || die "that is not a complete Hop.app"
  need_macos "$(plist_min "$1/Contents/Info.plist")"      # the app's own minimum, checked before the destination is touched
  codesign --verify --strict "$1" || die "the app's signature does not match its contents; nothing was installed"
  # A running Hop is found by its exact program path (compared as plain text, never as a pattern) and,
  # wherever it was started from, by its bundle id.
  if ps -axo comm= | grep -Fxq "$DEST/Contents/MacOS/Hop"; then
    die "Hop is running from $DEST. Quit it (menu bar icon, Quit Hop) and run this again. Nothing was installed."
  fi
  ELSEWHERE=$(lsappinfo list 2>/dev/null | grep -A2 -F "bundleID=\"$BUNDLE_ID\"" | sed -n 's/^ *bundle path="\(.*\)"$/\1/p' | head -n 1)
  if [ -n "$ELSEWHERE" ]; then
    if [ "${HOP_NO_OPEN:-}" = "1" ]; then
      say "note: a Hop is running from $ELSEWHERE; it is left alone and the new copy is not opened"
    else
      die "a Hop is already running from $ELSEWHERE. Quit it (menu bar icon, Quit Hop) and run this again. Nothing was installed."
    fi
  fi
  mkdir -p "$DEST_DIR"
  STAGED="$DEST_DIR/.Hop-install-$$.app"
  rm -rf "$STAGED"
  /usr/bin/ditto "$1" "$STAGED"
  BACKUP=""
  if [ -e "$DEST" ]; then
    mkdir -p "$DEST_DIR/.Hop-backups"
    BACKUP="$DEST_DIR/.Hop-backups/Hop-$(date -u +%Y%m%dT%H%M%SZ)-$$.app"
    mv "$DEST" "$BACKUP"
  fi
  if ! mv "$STAGED" "$DEST"; then
    [ -z "$BACKUP" ] || mv "$BACKUP" "$DEST"
    die "could not put Hop in $DEST_DIR"
  fi
  say "installed $DEST"
  [ -z "$BACKUP" ] || say "the app that was there before: $BACKUP"
  # The hop command for a terminal: `Hop link` writes ~/.local/bin/hop and leaves a file or another program's
  # link there alone. A release from before that command would open the app on the word, so it is asked only
  # when the program carries the command's own words.
  if [ "${HOP_NO_CLI:-}" != "1" ] && [ -z "${HOP_INSTALL_DIR:-}" ] && grep -a -q 'hop is already linked' "$DEST/Contents/MacOS/Hop"; then
    "$DEST/Contents/MacOS/Hop" link 2>&1 | sed 's/^/install.sh: /' || true
  fi
  if [ "${HOP_NO_OPEN:-}" = "1" ]; then say "not opened (HOP_NO_OPEN=1)"; else open "$DEST"; fi
}

from_download() {   # from_download <version> <zip sha256> [executable sha256]
  VERSION=$1; WANT=$2; WANT_EXE=${3:-}
  printf '%s' "$VERSION" | grep -Eq '^[0-9A-Za-z][0-9A-Za-z._-]*$' || die "that does not look like a version: $VERSION"
  is_sha "$WANT" || die "the expected sha256 must be 64 lower-case hex characters"
  [ -n "${HOP_DOWNLOAD_BASE:-}" ] || die "set HOP_DOWNLOAD_BASE to the folder the zip is served from"
  ZIP="$WORK/Hop-$VERSION.zip"
  say "downloading ${HOP_DOWNLOAD_BASE%/}/Hop-$VERSION.zip"
  fetch "${HOP_DOWNLOAD_BASE%/}/Hop-$VERSION.zip" "$ZIP"
  GOT=$(sha "$ZIP")
  if [ "$GOT" != "$WANT" ]; then
    say "expected sha256 $WANT" >&2
    say "got      sha256 $GOT" >&2
    die "the download does not match the expected sha256; nothing was installed"
  fi
  say "sha256 matches: $GOT"
  # Only Hop.app may come out of the zip.
  if unzip -Z1 "$ZIP" | grep -Ev '^Hop\.app(/|$)' | grep -q . || unzip -Z1 "$ZIP" | grep -Eq '(^|/)\.\.(/|$)'; then
    die "the zip holds something other than Hop.app; nothing was installed"
  fi
  mkdir "$WORK/unzipped"
  /usr/bin/ditto -x -k "$ZIP" "$WORK/unzipped"
  if [ -n "$WANT_EXE" ]; then
    [ "$(sha "$WORK/unzipped/Hop.app/Contents/MacOS/Hop")" = "$WANT_EXE" ] || die "the program inside the zip does not match RELEASE.json; nothing was installed"
    say "program sha256 matches RELEASE.json"
  fi
  install_app "$WORK/unzipped/Hop.app"
}

from_release() {   # from_release <RELEASE.json file or URL>
  J="$WORK/RELEASE.json"
  case "$1" in
    http://*|https://*|file://*) fetch "$1" "$J" ;;
    *) [ -f "$1" ] || die "no such file: $1"; cp "$1" "$J" ;;
  esac
  field() { plutil -extract "$1" raw -o - "$J" 2>/dev/null || die "RELEASE.json has no $1"; }
  V=$(field version); Z=$(field zip_sha256); E=$(field executable_sha256)
  need_macos "$(field minimum_macos)"                     # before the download
  is_sha "$E" || die "RELEASE.json: executable_sha256 is not a sha256"
  say "release $V, built from commit $(field source_commit)"
  from_download "$V" "$Z" "$E"
}

from_source() {   # from_source <git url> <commit>
  URL=$1; COMMIT=$2
  printf '%s' "$COMMIT" | grep -Eq '^[0-9a-f]{40}$' || die "give the full 40-character commit id, not a branch, tag or short id"
  command -v git >/dev/null 2>&1 && command -v swiftc >/dev/null 2>&1 || die "building needs Apple's Command Line Tools: xcode-select --install"
  SRC="$WORK/src"
  git clone --quiet --no-checkout "$URL" "$SRC" || die "could not clone $URL"
  git -C "$SRC" checkout --quiet --detach "$COMMIT" 2>/dev/null || die "commit $COMMIT is not in $URL; nothing was built"
  HEAD=$(git -C "$SRC" rev-parse HEAD)
  [ "$HEAD" = "$COMMIT" ] || die "checked out $HEAD, not $COMMIT; nothing was built"
  [ -z "$(git -C "$SRC" status --porcelain)" ] || die "the checkout is not clean; nothing was built"
  need_macos "$(plist_min "$SRC/Resources/Info.plist")"   # before the build
  say "building commit $HEAD"
  (cd "$SRC" && ./build.sh) || die "the build failed; nothing was installed"
  say "program sha256 $(sha "$SRC/build/Hop.app/Contents/MacOS/Hop")"
  install_app "$SRC/build/Hop.app"
}

case "${1:-}" in
  --from-source) [ $# -eq 3 ] || usage; from_source "$2" "$3" ;;
  --release)     [ $# -eq 2 ] || usage; from_release "$2" ;;
  -h|--help|"")  usage ;;
  -*)            usage ;;
  *)             [ $# -eq 2 ] || usage; from_download "$1" "$2" ;;
esac
