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

# InstaPods CLI installer
# Usage: curl -fsSL https://instapods.com/install.sh | sh

REPO="InstaPods/sdk"
GITHUB_BASE="https://github.com/${REPO}/releases"

main() {
  os=$(detect_os)
  arch=$(detect_arch)

  if [ -z "$os" ] || [ -z "$arch" ]; then
    echo "Error: Unsupported platform: $(uname -s)/$(uname -m)"
    echo "Supported: macOS (arm64, amd64), Linux (amd64, arm64)"
    exit 1
  fi

  binary="instapods-${os}-${arch}"

  # Resolve latest tag via GitHub API
  tag=$(resolve_latest_tag)
  url="${GITHUB_BASE}/download/${tag}/${binary}"

  echo "Installing instapods ${tag} for ${os}/${arch}..."
  echo ""

  # Download to temp file
  tmp=$(mktemp)
  trap 'rm -f "$tmp"' EXIT

  echo "Downloading ${url}..."
  if ! download_with_progress "$url" "$tmp"; then
    echo "Error: Failed to download ${url}"
    echo "Check https://instapods.com for manual download."
    exit 1
  fi

  # Verify checksum
  checksums_tmp=$(mktemp)
  trap 'rm -f "$tmp" "$checksums_tmp"' EXIT

  checksums_url="${GITHUB_BASE}/download/${tag}/checksums.txt"
  if download "$checksums_url" "$checksums_tmp" 2>/dev/null; then
    expected=$(grep "${binary}" "$checksums_tmp" | awk '{print $1}')
    if [ -n "$expected" ]; then
      actual=$(compute_sha256 "$tmp")
      if [ "$actual" != "$expected" ]; then
        echo "Error: Checksum mismatch"
        echo "  expected: ${expected}"
        echo "  got:      ${actual}"
        exit 1
      fi
      echo "Checksum verified."
    fi
  fi

  chmod +x "$tmp"

  # Install to /usr/local/bin or ~/.local/bin
  install_dir="/usr/local/bin"
  install_path="${install_dir}/instapods"
  needs_sudo=""

  if [ ! -w "$install_dir" ]; then
    if command -v sudo >/dev/null 2>&1; then
      needs_sudo="sudo"
    else
      # Fall back to ~/.local/bin
      install_dir="${HOME}/.local/bin"
      install_path="${install_dir}/instapods"
      mkdir -p "$install_dir"
    fi
  fi

  if [ -n "$needs_sudo" ]; then
    echo "Need sudo to install to ${install_dir}."
    $needs_sudo cp "$tmp" "$install_path" </dev/tty
    $needs_sudo chmod +x "$install_path" </dev/tty
  else
    cp "$tmp" "$install_path"
    chmod +x "$install_path"
  fi

  echo ""
  echo "Installed to ${install_path}"
  echo ""
  "${install_path}" version
  echo ""
  echo "Run 'instapods login' to get started."

  # Check if install dir is in PATH
  case ":${PATH}:" in
    *":${install_dir}:"*) ;;
    *)
      echo ""
      echo "Note: ${install_dir} is not in your PATH."
      echo "Add it with: export PATH=\"${install_dir}:\$PATH\""
      ;;
  esac
}

resolve_latest_tag() {
  # GitHub redirects /releases/latest to /releases/tag/<tag> — extract the tag
  if command -v curl >/dev/null 2>&1; then
    curl -fsSI "${GITHUB_BASE}/latest" 2>/dev/null | grep -i "^location:" | sed 's|.*/tag/||' | tr -d '\r\n'
  elif command -v wget >/dev/null 2>&1; then
    wget --spider -S "${GITHUB_BASE}/latest" 2>&1 | grep -i "^  Location:" | sed 's|.*/tag/||' | tr -d '\r\n'
  else
    echo "Error: curl or wget is required"
    exit 1
  fi
}

detect_os() {
  case "$(uname -s)" in
    Darwin) echo "darwin" ;;
    Linux)  echo "linux" ;;
    *)      echo "" ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64)  echo "amd64" ;;
    arm64|aarch64) echo "arm64" ;;
    *)             echo "" ;;
  esac
}

download() {
  url="$1"
  dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -o "$dest" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$dest" "$url"
  else
    echo "Error: curl or wget is required"
    exit 1
  fi
}

download_with_progress() {
  url="$1"
  dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fL --progress-bar -o "$dest" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget -O "$dest" "$url"
  else
    echo "Error: curl or wget is required"
    exit 1
  fi
}

compute_sha256() {
  file="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" | awk '{print $1}'
  else
    echo ""
  fi
}

main "$@"
