#!/bin/sh
# opsh installer: downloads a verified prebuilt binary into ~/.local/bin.
set -eu

REPO="opsh-dev/opsh"
BIN="opsh"

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

need() {
  command -v "$1" >/dev/null 2>&1 || err "$1 is required"
}

detect_os() {
  case "$(uname -s)" in
    Linux) printf 'linux' ;;
    Darwin) printf 'darwin' ;;
    *)
      err "unsupported operating system: $(uname -s). On Windows use https://opsh.dev/install.ps1"
      ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64 | amd64) printf 'x64' ;;
    arm64 | aarch64) printf 'arm64' ;;
    *) err "unsupported architecture: $(uname -m)" ;;
  esac
}

detect_libc() {
  case "$1" in
    linux) ;;
    *)
      printf 'glibc'
      return
      ;;
  esac
  # A glibc system can also have the musl loader installed (for example
  # Debian's musl package), so ask ldd which libc is actually running first.
  if command -v ldd >/dev/null 2>&1; then
    if ldd --version 2>&1 | grep -qi musl; then
      printf 'musl'
    else
      printf 'glibc'
    fi
    return
  fi
  if [ -e /lib/ld-musl-x86_64.so.1 ] || [ -e /lib/ld-musl-aarch64.so.1 ]; then
    printf 'musl'
    return
  fi
  printf 'glibc'
}

check_musl_runtime() {
  [ "$1" = "musl" ] || return 0
  found=0
  for lib in /usr/lib/libstdc++.so.6 /usr/lib64/libstdc++.so.6 /lib/libstdc++.so.6; do
    if [ -e "$lib" ]; then
      found=1
      break
    fi
  done
  [ "$found" = "1" ] || err "the musl build needs the libstdc++ runtime. Install it with \"apk add libstdc++\" (or your distribution's equivalent), then rerun this installer"
}

download() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --retry 3 --proto '=https' -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget -q --https-only -O "$2" "$1"
  else
    err "curl or wget is required"
  fi
}

verify_checksum() {
  expected="$(awk -v name="$3" '$2 == name || $2 == "*" name { print $1; exit }' "$2")"
  [ -n "$expected" ] || err "SHA256SUMS does not list $3"

  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "$1" | awk '{ print $1 }')"
  elif command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "$1" | awk '{ print $1 }')"
  else
    err "sha256sum or shasum is required"
  fi

  [ "$actual" = "$expected" ] || err "checksum mismatch for $3"
}

path_profile() {
  if [ -n "${OPSH_SHELL_PROFILE:-}" ]; then
    printf '%s' "$OPSH_SHELL_PROFILE"
    return
  fi
  case "${SHELL:-}" in
    */zsh) printf '%s' "$HOME/.zshrc" ;;
    */bash)
      if [ "$(uname -s)" = "Darwin" ] && [ -f "$HOME/.bash_profile" ]; then
        printf '%s' "$HOME/.bash_profile"
      elif [ -f "$HOME/.bashrc" ]; then
        printf '%s' "$HOME/.bashrc"
      elif [ -f "$HOME/.bash_profile" ]; then
        printf '%s' "$HOME/.bash_profile"
      else
        printf '%s' "$HOME/.bashrc"
      fi
      ;;
    */fish) printf '%s' "$HOME/.config/fish/config.fish" ;;
    *) printf '%s' "$HOME/.profile" ;;
  esac
}

configure_path() {
  dir="$1"

  if [ "${OPSH_NO_MODIFY_PATH:-}" = "1" ]; then
    say ""
    say "Add $dir to PATH:"
    say "  export PATH=\"$dir:\$PATH\""
    return 0
  fi

  case "$dir" in
    *'"'* | *'$'* | *'`'* | *'\'*)
      say ""
      say "Could not update the shell profile automatically."
      say "Add $dir to PATH:"
      say "  export PATH=\"$dir:\$PATH\""
      return 0
      ;;
  esac

  profile="$(path_profile)"
  if [ -f "$profile" ] && grep -q '>>> opsh installer >>>' "$profile"; then
    say ""
    say "$profile already contains an opsh PATH entry."
    say "Restart your shell or run: source \"$profile\""
    return 0
  fi

  mkdir -p "$(dirname "$profile")"
  case "$profile" in
    *config.fish)
      {
        printf '\n# >>> opsh installer >>>\n'
        printf 'if not contains "%s" $PATH\n' "$dir"
        printf '    set -gx PATH "%s" $PATH\n' "$dir"
        printf 'end\n'
        printf '# <<< opsh installer <<<\n'
      } >> "$profile"
      ;;
    *)
      {
        printf '\n# >>> opsh installer >>>\n'
        printf 'case ":$PATH:" in\n'
        printf '  *":%s:"*) ;;\n' "$dir"
        printf '  *) export PATH="%s:$PATH" ;;\n' "$dir"
        printf 'esac\n'
        printf '# <<< opsh installer <<<\n'
      } >> "$profile"
      ;;
  esac

  say ""
  say "Added $dir to PATH in $profile."
  say "Restart your shell or run: source \"$profile\""
  say "For this shell now: export PATH=\"$dir:\$PATH\""
}

main() {
  [ -n "${HOME:-}" ] || err "HOME is not set"
  [ -z "${OPSH_DEBUG:-}" ] || set -x

  need uname
  need mktemp
  need mkdir
  need chmod
  need mv
  need awk
  need sed
  need gzip
  need grep
  need dirname

  os="$(detect_os)"
  arch="$(detect_arch)"
  libc="$(detect_libc "$os")"
  check_musl_runtime "$libc"

  version="${OPSH_VERSION:-}"
  if [ -n "$version" ]; then
    version="$(printf '%s' "$version" | sed 's/^v//')"
    base="https://github.com/$REPO/releases/download/v$version"
  else
    base="https://github.com/$REPO/releases/latest/download"
  fi

  case "$libc" in
    musl) asset="opsh-$os-$arch-musl.gz" ;;
    *) asset="opsh-$os-$arch.gz" ;;
  esac
  install_dir="${OPSH_INSTALL_DIR:-$HOME/.local/bin}"
  tmp="$(mktemp -d "${TMPDIR:-/tmp}/opsh-install.XXXXXX")"
  trap 'rm -rf "$tmp"' EXIT

  say "Downloading $asset"
  download "$base/$asset" "$tmp/$asset"
  download "$base/SHA256SUMS" "$tmp/SHA256SUMS"

  say "Verifying checksum"
  verify_checksum "$tmp/$asset" "$tmp/SHA256SUMS" "$asset"

  say "Installing to $install_dir"
  mkdir -p "$install_dir"
  gzip -dc "$tmp/$asset" > "$tmp/$BIN"
  chmod 755 "$tmp/$BIN"
  mv -f "$tmp/$BIN" "$install_dir/$BIN"

  say ""
  "$install_dir/$BIN" --version || true

  configure_path "$install_dir"
}

main "$@"
