#!/bin/sh
# Installs or updates prontaro on Linux or macOS: reads the latest version, downloads its archive and SHA256SUMS,
# checks the sum, and replaces the program in one rename in /usr/local/bin (or ~/.local/bin) - a failure leaves
# the installed version as it was. Running it again updates. On a terminal it offers to add the install directory
# to your shell profile (if not already in PATH) and to install shell completion.
#
#   curl -fsSL https://prontaro.com/install.sh | sh
#   curl -fsSL https://prontaro.com/install.sh | PRONTARO_VERSION=1.0.0 sh     - a given version
#
# PRONTARO_DOWNLOAD_URL   - another release place (scripts/release.sh fills in the default when it publishes this).
# PRONTARO_INSTALL_DIR    - install into this directory instead of /usr/local/bin or ~/.local/bin.
# PRONTARO_NO_MODIFY_PATH - set to 1 to skip the interactive prompt to update your shell profile.
set -eu

base="${PRONTARO_DOWNLOAD_URL:-https://dl.prontaro.net/cli}"
version="${PRONTARO_VERSION:-}"
automatic=""
[ -n "$version" ] || automatic=1

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

# The archive and its sum come from one place: only https keeps anyone on the way from changing both.
while :; do
  case "$base" in
    */) base="${base%/}" ;;
    *) break ;;
  esac
done
case "$base" in
  https://?*) ;;
  @*) die "Set PRONTARO_DOWNLOAD_URL to the release place (this copy of the script is not a published one)" ;;
  *) die "PRONTARO_DOWNLOAD_URL must start with https:// (got $base)" ;;
esac

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *) die "This installer is for Linux and macOS; on Windows use install.ps1 in PowerShell" ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *) die "No build for $(uname -m)" ;;
esac
# Detect Rosetta 2 on Apple Silicon Macs running an x86_64 shell.
if [ "$os" = darwin ] && [ "$arch" = amd64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = "1" ]; then
  arch=arm64
fi

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL --proto '=https' --proto-redir '=https' -o "$2" "$1"; }
elif command -v wget >/dev/null 2>&1; then
  if wget --help 2>&1 | grep -q -- '--https-only'; then
    fetch() { wget -q --https-only -O "$2" "$1"; }
  else
    say "! BusyBox wget cannot block HTTPS-to-HTTP redirects; install curl for strict redirect checks"
    fetch() { wget -q -O "$2" "$1"; }
  fi
else
  die "Need curl or wget"
fi

if command -v sha256sum >/dev/null 2>&1; then
  sum() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null 2>&1; then
  sum() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
  die "Need sha256sum or shasum to check the download"
fi

# not_ours refuses a prontaro another installer put at $1: overwriting it would leave a second copy that hides
# or is hidden by it, or break that installer's updates. Its own update command is the way.
not_ours() {
  case "$1" in
    /opt/homebrew/bin/*) die "prontaro is installed with Homebrew ($1); update it with: brew upgrade prontaro/tap/prontaro" ;;
  esac
  real="$(readlink -f "$1" 2>/dev/null || readlink "$1" 2>/dev/null || printf '%s' "$1")"
  case "$real" in
    */Cellar/*) die "prontaro is installed with Homebrew ($1); update it with: brew upgrade prontaro/tap/prontaro" ;;
  esac
  die "prontaro is installed at $1, not by this script; update it the way it was installed, or remove it and run this again"
}

# Where to put it: PRONTARO_INSTALL_DIR if set; else an existing script-managed prontaro in PATH;
# else /usr/local/bin (created when root) if writable; else ~/.local/bin when HOME is set.
home_dir="${HOME:-}"
dest=""
if [ -n "${PRONTARO_INSTALL_DIR:-}" ]; then
  dest="$PRONTARO_INSTALL_DIR"
  mkdir -p "$dest" || die "Can't create PRONTARO_INSTALL_DIR ($dest)"
else
  found="$(command -v prontaro 2>/dev/null || true)"
  if [ -n "$found" ]; then
    if [ "$found" = "/usr/local/bin/prontaro" ] || { [ -n "$home_dir" ] && [ "$found" = "$home_dir/.local/bin/prontaro" ]; }; then
      dest="$(dirname "$found")"
    else
      not_ours "$found"
    fi
  fi
  if [ -z "$dest" ]; then
    if [ "$(id -u)" -eq 0 ]; then
      mkdir -p /usr/local/bin 2>/dev/null || true
      if [ -w /usr/local/bin ]; then
        dest=/usr/local/bin
      else
        die "/usr/local/bin is not writable. Set PRONTARO_INSTALL_DIR=/path/to/bin"
      fi
    elif [ -w /usr/local/bin ]; then
      dest=/usr/local/bin
    elif [ -n "$home_dir" ]; then
      dest="$home_dir/.local/bin"
      mkdir -p "$dest"
    else
      die "HOME is not set and /usr/local/bin is not writable. Set PRONTARO_INSTALL_DIR=/path/to/bin"
    fi
  fi
fi
case "$dest" in
  /) ;;
  */) dest="${dest%/}" ;;
esac

# What is at the destination now - found by PATH or not - is replaced only when it is a plain file (this
# script's): a link is another installer's, anything else is not a program to replace.
bin="$dest/prontaro"
updating=""
if [ -L "$bin" ]; then
  not_ours "$bin"
elif [ -e "$bin" ]; then
  [ -f "$bin" ] || die "$bin is not a file; remove it and run this again"
  updating=1
fi
[ -w "$dest" ] || die "prontaro goes to $dest, which this user can't write; run this again with sudo: ... | sudo sh"

tmp="$(mktemp -d)"
new=""
trap 'rm -rf "$tmp"; [ -z "$new" ] || rm -f "$new"' EXIT
trap 'exit 1' INT TERM

case "$version" in
  "")
    fetch "$base/latest.json" "$tmp/latest.json" || die "Can't download $base/latest.json"
    # The pointer is exactly {"version":"X.Y.Z"} (scripts/release.sh writes it; this script is fetched anew
    # each time, so the two change together), with blanks allowed only between its parts: anything else - cut,
    # an error page, a changed key or value - is no version. Line ends become blanks, never glue.
    version="$(tr '\r\n\t' '   ' <"$tmp/latest.json" |
      sed -n 's/^ *{ *"version" *: *"\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)" *} *$/\1/p')"
    [ -n "$version" ] || die "$base/latest.json is not {\"version\":\"X.Y.Z\"}. Nothing changed; try again later."
    ;;
  v*) version="${version#v}" ;;
esac
printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || die "Not a version: \"$version\" (want X.Y.Z)"
if [ -n "$automatic" ] && [ -n "$updating" ]; then
  current="$("$bin" version 2>/dev/null | sed -n 's/^prontaro \([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -n 1)"
  [ -n "$current" ] || die "Can't read the installed version; set PRONTARO_VERSION explicitly. Nothing changed."
  if awk -v old="$current" -v new="$version" 'BEGIN { split(old,a,"."); split(new,b,"."); for (i=1;i<=3;i++) { if (a[i]+0>b[i]+0) exit 0; if (a[i]+0<b[i]+0) exit 1 } exit 1 }'; then
    die "Installed prontaro $current is newer than available $version. Nothing changed."
  fi
fi

archive="prontaro_${os}_${arch}.tar.gz"
url="$base/v$version"
say "Downloading prontaro $version ($os/$arch)..."
fetch "$url/$archive" "$tmp/$archive" || die "Can't download $url/$archive"
fetch "$url/SHA256SUMS" "$tmp/SHA256SUMS" || die "Can't download $url/SHA256SUMS"

want="$(awk -v f="$archive" '$2 == f || $2 == "*" f { print $1 }' "$tmp/SHA256SUMS")"
[ -n "$want" ] || die "$archive is not in SHA256SUMS. Nothing changed."
got="$(sum "$tmp/$archive")"
[ "$want" = "$got" ] || die "Checksum mismatch for $archive: expected $want, got $got. Nothing changed."

tar -xzf "$tmp/$archive" -C "$tmp" prontaro || die "The archive has no prontaro inside. Nothing changed."

# The new file is written beside the old one and renamed over it: one step on the same file system, so a
# service starting now finds the old file or the new one, never half of one.
new="$(mktemp "$dest/.prontaro.XXXXXX")" || die "Can't write to $dest. Nothing changed."
cat "$tmp/prontaro" >"$new" || die "Can't write to $dest. Nothing changed."
chmod 0755 "$new"
mv -f "$new" "$bin" || die "Can't replace $bin. Nothing changed."
new=""
say "OK Installed prontaro $version: $bin"
[ -z "$updating" ] || say "  Running prontaro processes and services keep the old version until they restart."

in_path=""
case ":$PATH:" in
  *":$dest:"*) in_path=1 ;;
esac
quoted_dest=$(printf '%s' "$dest" | sed "s/'/'\\\\''/g")
quoted_bin=$(printf '%s' "$bin" | sed "s/'/'\\\\''/g")
next_bin=prontaro
added_rc=""
rc_file=""
if [ -z "$in_path" ]; then
  next_bin="'$quoted_bin'"
  shell_name="$(basename "${SHELL:-}")"
  if [ -n "$home_dir" ]; then
    case "$shell_name" in
      zsh) rc_file="$home_dir/.zshrc" ;;
      bash)
        if [ "$os" = darwin ] && [ -f "$home_dir/.bash_profile" ]; then
          rc_file="$home_dir/.bash_profile"
        else
          rc_file="$home_dir/.bashrc"
        fi
        ;;
      *) rc_file="$home_dir/.profile" ;;
    esac
  fi
  if [ -n "$home_dir" ] && [ "$dest" = "$home_dir/.local/bin" ]; then
    path_line='export PATH="$HOME/.local/bin:$PATH"'
  else
    path_line="export PATH='$quoted_dest':\"\$PATH\""
  fi
  quoted_path_line=$(printf '%s' "$path_line" | sed "s/'/'\\\\''/g")
  in_rc=""
  if [ -n "$rc_file" ] && [ -f "$rc_file" ]; then
    if grep -Fq "$path_line" "$rc_file" 2>/dev/null || grep -Fq "$dest" "$rc_file" 2>/dev/null; then
      in_rc=1
    fi
  fi
  wrote_err=""
  if [ -z "${PRONTARO_NO_MODIFY_PATH:-}" ] && [ -n "$rc_file" ] && [ -z "$in_rc" ] && [ -t 2 ] && { : </dev/tty; } 2>/dev/null; then
    printf '? Add %s to %s? [Y/n] ' "$dest" "$rc_file" >&2
    read -r answer </dev/tty || answer=""
    case "$answer" in
      "" | y | Y | yes | YES)
        if printf '\n# prontaro\n%s\n' "$path_line" >> "$rc_file" 2>/dev/null; then
          added_rc=1
          say "OK Added $dest to $rc_file"
        else
          wrote_err=1
          say "! Can't write $rc_file; add manually: echo '$quoted_path_line' >> $rc_file"
        fi
        ;;
    esac
  fi
  if [ -z "$added_rc" ] && [ -z "$in_rc" ] && [ -z "$wrote_err" ]; then
    if [ -n "$rc_file" ]; then
      say "! $dest is not in your PATH. To add it permanently: echo '$quoted_path_line' >> $rc_file"
    else
      say "! $dest is not in your PATH."
    fi
  fi
fi

if [ "$dest" != /usr/local/bin ]; then
  say "  A system service of root needs a root-owned prontaro: run this installer with sudo (... | sudo sh)."
fi

# Completion for the current shell - only on a terminal, only with consent. With `curl ... | sh` stdin is the
# script, so the question is asked on the terminal itself.
if [ -n "$home_dir" ] && [ -t 2 ] && { : </dev/tty; } 2>/dev/null; then
  shell="$(basename "${SHELL:-}")"
  case "$shell" in
    bash) target="${XDG_DATA_HOME:-$home_dir/.local/share}/bash-completion/completions/prontaro" ;;
    fish) target="${XDG_CONFIG_HOME:-$home_dir/.config}/fish/completions/prontaro.fish" ;;
    zsh) target="" ;;
    *) target="" ;;
  esac
  if [ -n "$target" ] && [ ! -e "$target" ]; then
    printf '? Install %s completion for prontaro into %s? [y/N] ' "$shell" "$target" >&2
    read -r answer </dev/tty || answer=""
    case "$answer" in
      y | Y | yes)
        mkdir -p "$(dirname "$target")"
        "$bin" completion "$shell" >"$target" && say "OK Completion installed; it works in new $shell sessions."
        ;;
    esac
  elif [ "$shell" = zsh ] && [ ! -e "$home_dir/.zsh/completions/_prontaro" ]; then
    say "  Completion for zsh: mkdir -p ~/.zsh/completions && $next_bin completion zsh > ~/.zsh/completions/_prontaro"
    say "  Then add fpath=(~/.zsh/completions \$fpath) before compinit in ~/.zshrc."
  fi
fi

if [ -n "$in_path" ]; then
  say "  Next: prontaro login"
elif [ -n "$added_rc" ]; then
  say "  Next: source $rc_file && prontaro login"
else
  say "  Next: export PATH='$quoted_dest':\"\$PATH\" && prontaro login"
fi
