#!/usr/bin/env sh
set -eu

server=https://repopack.com
project=${RP_PROJECT:-repopack}
app=${RP_APP:-cli}
ref=${RP_REF:-latest}
metadata_url=${RP_METADATA_URL:-$server/api/v0/cli/version}
install_root=${RP_INSTALL:-}
no_link=${RP_NO_LINK:-0}
if [ -n "$install_root" ]; then
  bin_dir=$install_root/bin
else
  bin_dir=$HOME/.local/bin
fi
exe=$bin_dir/rp
link_dir=$HOME/.local/bin
link=$link_dir/rp
legacy_exe=$HOME/.rp/bin/rp

error() {
  echo "error: $*" >&2
  exit 1
}

need() {
  command -v "$1" >/dev/null 2>&1 || error "missing required command: $1"
}

sha256_file() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif command -v openssl >/dev/null 2>&1; then
    openssl dgst -sha256 "$1" | awk '{print $NF}'
  else
    error "missing required command: sha256sum, shasum, or openssl"
  fi
}

# -ef is not POSIX, but dash, bash, ksh, zsh, and busybox sh all support it.
same_file() {
  # shellcheck disable=SC3013
  [ "$1" -ef "$2" ]
}

configure_profile() {
  if [ -n "$profile" ] && [ ! -L "$profile" ] && [ -f "$profile" ] && [ -r "$profile" ] && [ -w "$profile" ]; then
    marked_line="$command_line # rp installer PATH"
    if awk -v expected="$command_line" -v marked="$marked_line" '$0 == expected || $0 == marked { found=1 } END { exit !found }' "$profile"; then
      echo "PATH setup already present in $profile; open a new shell or run: $reload"
      return
    fi
    if [ ! -L "$profile" ] && [ -f "$profile" ] && [ -w "$profile" ] &&
       printf '\n%s\n' "$marked_line" >>"$profile"; then
      echo "added $path_dir to PATH in $profile; open a new shell or run: $reload"
      return
    fi
  fi
  if [ -n "$profile" ]; then
    echo "Add this line to $profile, then open a new shell:"
  else
    echo 'Add this line to your shell profile, then open a new shell:'
  fi
  echo "  $command_line"
  [ -z "$reload" ] || echo "After editing, reload with: $reload"
}

configure_path() {
  path_dir=$1
  case ":${PATH:-}:" in
    *:"$path_dir":*) return ;;
  esac
  if [ "$path_dir" != "$HOME/.local/bin" ]; then
    echo "note: add $path_dir to PATH in your shell profile to run rp by name"
    return
  fi

  shell_name=${SHELL:-}
  shell_name=${shell_name##*/}
  profile=
  reload=
  command_line='export PATH="$HOME/.local/bin:$PATH"'
  case "$shell_name" in
    bash)
      # Login Bash reads the first existing file from this ordered list;
      # interactive non-login Bash reads .bashrc. They need not source each other.
      profile=$HOME/.bashrc
      if [ -e "$profile" ] || [ -L "$profile" ]; then
        reload=". "$profile""
        configure_profile
      else
        echo 'Add this line to ~/.bashrc for interactive non-login Bash, then open a new shell:'
        echo "  $command_line"
      fi
      login_profile=
      for candidate in "$HOME/.bash_profile" "$HOME/.bash_login" "$HOME/.profile"; do
        if [ -e "$candidate" ] || [ -L "$candidate" ]; then
          login_profile=$candidate
          break
        fi
      done
      if [ -n "$login_profile" ]; then
        profile=$login_profile
        reload=". "$profile""
        configure_profile
      else
        echo 'Add this line to a Bash login profile (e.g. ~/.bash_profile), then open a new shell:'
        echo "  $command_line"
      fi
      return
      ;;
    zsh) profile=$HOME/.zshrc; reload='. "$HOME/.zshrc"' ;;
    fish)
      profile=$HOME/.config/fish/config.fish
      command_line='set -gx PATH "$HOME/.local/bin" $PATH'
      reload='source "$HOME/.config/fish/config.fish"'
      ;;
  esac
  configure_profile
}

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  *) error "unsupported OS: $(uname -s)" ;;
esac

case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) error "unsupported architecture: $(uname -m)" ;;
esac

target=$os-$arch
mkdir -p "$bin_dir" || error "failed to create $bin_dir"
tmp=$(mktemp -d "$bin_dir/.rp-install.XXXXXX") || error "failed to stage installation in $bin_dir"

cleanup() {
  rm -rf "$tmp"
}
trap cleanup EXIT INT TERM

need chmod
need mkdir
need awk
need cut
need grep
need tr
need mktemp
if command -v curl >/dev/null 2>&1; then
  fetch='curl -fsSL'
elif command -v wget >/dev/null 2>&1; then
  fetch='wget -qO-'
else
  error "missing required command: curl or wget"
fi

echo "Repopack CLI installer"
echo "server:  $server"
echo "release: $project/$app@$ref"
echo "target:  $target"
echo "install: $exe"
echo

echo "fetching artifact metadata $metadata_url"
# shellcheck disable=SC2086
$fetch "$metadata_url" > "$tmp/latest.json" || error "failed to fetch artifact metadata"
artifact=$(tr '{' '
' < "$tmp/latest.json" | grep '"name":"rp-[^"]*-'"$target"'"' | head -n 1)
url=$(printf '%s
' "$artifact" | grep -o '"url":"[^"]*"' | cut -d '"' -f 4 | head -n 1)
expected_sha256=$(printf '%s
' "$artifact" | grep -o '"sha256":"[^"]*"' | cut -d '"' -f 4 | head -n 1)
if [ -z "$url" ]; then
  error "no artifact found for $target"
fi
if [ -z "$expected_sha256" ]; then
  error "artifact metadata is missing sha256 for $target"
fi
case "$url" in
  http://* | https://*) ;;
  /*) url="$server$url" ;;
  *) error "invalid artifact url: $url" ;;
esac

echo "downloading $url"
# shellcheck disable=SC2086
$fetch "$url" > "$tmp/rp" || error "failed to download rp for $target"
actual_sha256=$(sha256_file "$tmp/rp")
if [ "$actual_sha256" != "$expected_sha256" ]; then
  error "downloaded rp sha256 $actual_sha256 does not match expected $expected_sha256"
fi
echo "verified sha256 $actual_sha256"
chmod +x "$tmp/rp"

legacy=0
if [ "$exe" = "$link" ] && [ -L "$exe" ]; then
  # Only the symlink created by the old rp installer belongs to this migration.
  [ "$(readlink "$exe")" = "$legacy_exe" ] && [ -f "$legacy_exe" ] && [ ! -L "$legacy_exe" ] &&
    [ ! -L "$HOME/.rp" ] && [ ! -L "$HOME/.rp/bin" ] || error "refusing an unrelated or unsafe symlink at $exe"
  legacy=1
elif [ -e "$exe" ]; then
  [ -f "$exe" ] && [ ! -L "$exe" ] || error "refusing non-regular installation $exe"
  [ "$(sha256_file "$exe")" = "$actual_sha256" ] || error "refusing to replace existing $exe; use its own updater or inspect it first"
fi

if [ ! -e "$exe" ] || [ "$legacy" -eq 1 ]; then
  mv -f "$tmp/rp" "$exe" || error "failed to install $exe"
fi

echo "installed rp to $exe"

if [ "$legacy" -eq 1 ]; then
  if rm -f "$legacy_exe"; then
    rmdir "$HOME/.rp/bin" 2>/dev/null || :
    rmdir "$HOME/.rp" 2>/dev/null || :
    [ ! -d "$HOME/.rp" ] || echo "note: left other files in $HOME/.rp untouched"
  else
    echo "note: could not remove old $legacy_exe; remove it manually after verifying $exe"
  fi
fi

# Headless agent harnesses often skip shell startup files, so also expose rp
# in the conventional per-user bin directory. Only a missing or dangling entry
# is (re)created; never replace a file or link that is not ours.
if [ "$exe" != "$link" ] && [ "$no_link" = 0 ]; then
  if same_file "$link" "$exe"; then
    if [ -L "$link" ]; then
      echo "linked $link -> $exe"
    fi
  elif [ -e "$link" ]; then
    echo "note: $link already exists and is not a link to $exe; left unchanged"
    printf '  to replace it: ln -sf "%s" "%s"\n' "$exe" "$link"
  elif mkdir -p "$link_dir" && rm -f "$link" && ln -s "$exe" "$link"; then
    echo "linked $link -> $exe"
  else
    echo "note: could not link $link"
  fi
fi

echo
found=$(command -v rp 2>/dev/null || true)
if [ -n "$found" ] && same_file "$found" "$exe"; then
  echo "rp is on PATH: $found"
else
  if [ "$exe" != "$link" ] && [ -L "$link" ] && same_file "$link" "$exe"; then
    path_dir=$link_dir
  else
    path_dir=$bin_dir
  fi
  if [ -n "$found" ]; then
    echo "rp on PATH is $found, not this install."
    echo "To use this installation, put $path_dir before $found on PATH or run $exe directly."
  else
    echo "rp is not on PATH: $path_dir is not in PATH for this shell."
  fi
  echo "Run it by absolute path (no PATH changes needed):"
  echo "  $exe"
  configure_path "$path_dir"
fi
