#!/bin/sh
# datastore CLI installer:  curl -fsSL https://datastore.84-8-251-208.sslip.io/install.sh | sh
#
# No root needed. Installs into /usr/local/bin when it is writable (root, and
# many Macs); that is on PATH everywhere, so `datastore` works straight away.
# Otherwise installs into ~/.local/bin and adds that to PATH in the shell's
# startup file.
#
# On Linux x64 a helper binary that `datastore download` uses is installed next
# to the CLI (same directory). It is not a service and needs no setup. macOS
# gets the CLI only.
#
#   DATASTORE_VERSION=vX.Y.Z        install a specific release
#   DATASTORE_INSTALL_DIR=/opt/bin  install somewhere else (PATH left to you)
#   DATASTORE_PLUGIN_DIR=/opt/bin   put the helper somewhere else (default: next
#                                   to the CLI, where the CLI looks for it)
#   DATASTORE_NO_MODIFY_PATH=1      never edit shell startup files
#   DATASTORE_PLUGIN=auto|1|0       auto (default): install the helper on Linux
#                                   x64; 1 (= --with-plugin) fails when it
#                                   cannot be installed; 0 (= --no-plugin) skips it
set -eu

WITH_PLUGIN="${DATASTORE_PLUGIN:-${DATASTORE_WITH_PLUGIN:-auto}}"
for arg in "$@"; do
  case "$arg" in
    --with-plugin) WITH_PLUGIN=1 ;;
    --no-plugin) WITH_PLUGIN=0 ;;
    --no-login) ;; # accepted for old instructions; the installer never signs in
    *)
      echo "datastore: unknown option $arg" >&2
      exit 1
      ;;
  esac
done
case "$WITH_PLUGIN" in
  ""|0|false|no) WITH_PLUGIN="" ;;
  auto) WITH_PLUGIN=auto ;;
  *) WITH_PLUGIN=1 ;;
esac

VERSION="${DATASTORE_VERSION:-v0.14.1}"
ORIGIN="${DATASTORE_ORIGIN:-https://datastore.84-8-251-208.sslip.io}"
SYSTEM_DIR="${DATASTORE_SYSTEM_DIR:-/usr/local/bin}"
USER_DIR="${HOME}/.local/bin"

on_path() {
  case ":${PATH}:" in
    *":$1:"*) return 0 ;;
  esac
  return 1
}

case "$(uname -s):$(uname -m)" in
  Linux:x86_64|Linux:amd64) artifact="datastore-linux-x64"; plugin="datastore-plugin-linux-x64" ;;
  Linux:aarch64|Linux:arm64) artifact="datastore-linux-arm64"; plugin="datastore-plugin-linux-arm64" ;;
  Darwin:arm64|Darwin:aarch64) artifact="datastore-darwin-arm64"; plugin="datastore-plugin-darwin-arm64" ;;
  *)
    echo "datastore: unsupported platform $(uname -s) $(uname -m)" >&2
    echo "Supported: Linux x86-64, Linux ARM64 (aarch64), macOS on Apple Silicon. On Windows use WSL2 (Linux x86-64)." >&2
    exit 1
    ;;
esac

# The helper is built for Linux (x64 and arm64) and macOS (Apple Silicon). Elsewhere auto quietly skips it.
if [ -z "$plugin" ]; then
  if [ "$WITH_PLUGIN" = 1 ]; then
    echo "datastore: --with-plugin is only available on Linux and macOS (Apple Silicon)" >&2
    exit 1
  fi
  WITH_PLUGIN=""
fi

if [ -n "${DATASTORE_INSTALL_DIR:-}" ]; then
  INSTALL_DIR="$DATASTORE_INSTALL_DIR"
elif [ -d "$SYSTEM_DIR" ] && [ -w "$SYSTEM_DIR" ] && on_path "$SYSTEM_DIR"; then
  INSTALL_DIR="$SYSTEM_DIR"
else
  INSTALL_DIR="$USER_DIR"
fi
PLUGIN_DIR="${DATASTORE_PLUGIN_DIR:-$INSTALL_DIR}"

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

# verify <file> <file.sha256>
verify() {
  expected="$(awk '{print $1}' "$2")"
  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "$1" | awk '{print $1}')"
  else
    actual="$(shasum -a 256 "$1" | awk '{print $1}')"
  fi
  if [ -z "$expected" ] || [ "$actual" != "$expected" ]; then
    echo "datastore: checksum verification failed for $(basename "$1")" >&2
    exit 1
  fi
}

# place <file> <dir> <name>: copy next to the target, then rename over it, so a
# running copy keeps its inode and nobody sees a half-written binary.
place() {
  chmod 0755 "$1"
  cp "$1" "$2/.$3.new"
  mv "$2/.$3.new" "$2/$3"
}

# Everything is downloaded and verified before anything is installed.
echo "Installing datastore ${VERSION}..."
curl -fsSL "${ORIGIN}/releases/${VERSION}/${artifact}" -o "${tmp_dir}/${artifact}"
curl -fsSL "${ORIGIN}/releases/${VERSION}/${artifact}.sha256" -o "${tmp_dir}/${artifact}.sha256"
verify "${tmp_dir}/${artifact}" "${tmp_dir}/${artifact}.sha256"

plugin_note=""
if [ -n "$WITH_PLUGIN" ]; then
  # Auto mode stays quiet about a release that has no helper (older versions).
  if [ "$WITH_PLUGIN" = 1 ]; then quiet="-fsSL"; else quiet="-fsL"; fi
  if curl "$quiet" "${ORIGIN}/releases/${VERSION}/${plugin}" -o "${tmp_dir}/${plugin}" \
    && curl "$quiet" "${ORIGIN}/releases/${VERSION}/${plugin}.sha256" -o "${tmp_dir}/${plugin}.sha256"; then
    # A bad checksum always stops the install, in auto mode too.
    verify "${tmp_dir}/${plugin}" "${tmp_dir}/${plugin}.sha256"
  elif [ "$WITH_PLUGIN" = 1 ]; then
    echo "datastore: ${VERSION} is not complete for this platform (--with-plugin)" >&2
    exit 1
  else
    WITH_PLUGIN=""
    plugin_note="Note: some downloads need a newer version; run datastore update later."
  fi
fi

mkdir -p "$INSTALL_DIR"
# An older copy in ~/.local/bin could shadow the new one on PATH; keep it current.
if [ "$INSTALL_DIR" != "$USER_DIR" ] && [ -f "${USER_DIR}/datastore" ]; then
  place "${tmp_dir}/${artifact}" "$USER_DIR" datastore
fi
place "${tmp_dir}/${artifact}" "$INSTALL_DIR" datastore
cli_version="$("${INSTALL_DIR}/datastore" --version 2>/dev/null)" || cli_version="${VERSION#v}"

if [ -n "$WITH_PLUGIN" ]; then
  mkdir -p "$PLUGIN_DIR"
  if [ "$PLUGIN_DIR" != "$USER_DIR" ] && [ -f "${USER_DIR}/datastore-plugin" ]; then
    place "${tmp_dir}/${plugin}" "$USER_DIR" datastore-plugin
  fi
  place "${tmp_dir}/${plugin}" "$PLUGIN_DIR" datastore-plugin
  # The helper is installed silently; only a helper that cannot run is reported.
  if ! "${PLUGIN_DIR}/datastore-plugin" --version >/dev/null 2>&1; then
    echo "datastore: some downloads will not work: programs in ${PLUGIN_DIR} cannot run here (is it mounted noexec?)" >&2
    if [ "$WITH_PLUGIN" = 1 ]; then exit 1; fi
  fi
fi
echo "Installed datastore ${cli_version} to ${INSTALL_DIR}/datastore"
if [ -n "$plugin_note" ]; then echo "$plugin_note"; fi

if on_path "$INSTALL_DIR"; then
  echo "Run: datastore login"
  exit 0
fi

# Not on PATH yet. Only our own default directory is added automatically; a
# custom DATASTORE_INSTALL_DIR is the caller's to manage.
if [ -n "${DATASTORE_NO_MODIFY_PATH:-}" ] || [ "$INSTALL_DIR" != "$USER_DIR" ]; then
  echo "Add ${INSTALL_DIR} to PATH, then run: datastore login"
  exit 0
fi

case "$(basename "${SHELL:-sh}")" in
  zsh)
    profile="${ZDOTDIR:-$HOME}/.zshrc"
    line="export PATH=\"${INSTALL_DIR}:\$PATH\""
    ;;
  bash)
    # macOS terminals start login shells, which read .bash_profile, not .bashrc.
    if [ "$(uname -s)" = Darwin ]; then profile="$HOME/.bash_profile"; else profile="$HOME/.bashrc"; fi
    line="export PATH=\"${INSTALL_DIR}:\$PATH\""
    ;;
  fish)
    profile="${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/datastore.fish"
    line="contains -- ${INSTALL_DIR} \$PATH; or set -gx PATH ${INSTALL_DIR} \$PATH"
    ;;
  *)
    profile="$HOME/.profile"
    line="export PATH=\"${INSTALL_DIR}:\$PATH\""
    ;;
esac

if [ -f "$profile" ] && grep -qxF "$line" "$profile"; then
  echo "${INSTALL_DIR} is already added to PATH in ${profile}."
else
  mkdir -p "$(dirname "$profile")"
  printf '\n# Added by the datastore installer\n%s\n' "$line" >> "$profile"
  echo "Added ${INSTALL_DIR} to PATH in ${profile}."
fi
echo "Open a new terminal and run: datastore login"
echo "(or use it in this one right away: ${INSTALL_DIR}/datastore login)"
