#!/bin/sh
# install.sh — generated by forjar dist (do not edit)
# Rust-native Infrastructure as Code
# Usage: curl -sSf https://example.com/install.sh | sh
# Pinned: curl -sSf https://example.com/install.sh | sh -s -- --version v1.0.0
set -eu

BINARY="forjar"
REPO="paiml/forjar"
INSTALL_DIR="/usr/local/bin"
FALLBACK_DIR="~/.local/bin"
TAG=""
FORCE=0
YES=0
PREFIX=""

# ── Argument parsing ──

while [ $# -gt 0 ]; do
  case "$1" in
    --version) TAG="$2"; shift 2 ;;
    --prefix)  PREFIX="$2"; shift 2 ;;
    --force)   FORCE=1; shift ;;
    --yes|-y)  YES=1; shift ;;
    --help|-h) usage; exit 0 ;;
    *) die "unknown option: $1" ;;
  esac
done

# ── Output helpers ──

RED='' GREEN='' YELLOW='' BOLD='' RESET=''
if [ -t 1 ]; then
  RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'
  BOLD='\033[1m'; RESET='\033[0m'
fi

info()  { printf '%s%s%s %s\n' "$GREEN" "info:" "$RESET" "$1"; }
warn()  { printf '%s%s%s %s\n' "$YELLOW" "warn:" "$RESET" "$1" >&2; }
die()   { printf '%s%s%s %s\n' "$RED" "error:" "$RESET" "$1" >&2; exit 1; }

usage() {
  cat <<USAGE
Install forjar

USAGE:
    curl -sSf <url> | sh
    curl -sSf <url> | sh -s -- [OPTIONS]

OPTIONS:
    --version <TAG>   Install a specific version (e.g., v1.0.0)
    --prefix <DIR>    Install to a custom directory
    --force           Overwrite existing binary
    --yes, -y         Non-interactive mode
    --help, -h        Show this help
USAGE
}

# ── Platform detection ──

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

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

detect_libc() {
  if [ "$(detect_os)" != "linux" ]; then
    echo "none"
    return
  fi
  if ldd --version 2>&1 | grep -qi musl; then
    echo "musl"
  elif command -v ldd >/dev/null 2>&1; then
    echo "gnu"
  else
    echo "musl"
  fi
}

# ── Download helpers ──

download() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO- "$1"
  else
    die "curl or wget required"
  fi
}

download_file() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$2" "$1"
  else
    die "curl or wget required"
  fi
}

compute_checksum() {
  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}'
  else
    warn "no sha256sum or shasum found -- skipping checksum"
    echo ""
  fi
}

verify_checksum() {
  SUMS_URL="https://github.com/${REPO}/releases/download/${TAG}/SHA256SUMS"
  info "downloading checksums..."
  CHECKSUMS=$(download "$SUMS_URL") || die "failed to download checksums"
  EXPECTED=$(echo "$CHECKSUMS" | grep "$ASSET" | awk '{print $1}')
  if [ -z "$EXPECTED" ]; then
    warn "no checksum found for $ASSET — skipping verification"
    return
  fi
  ACTUAL=$(compute_checksum "$ARCHIVE")
  if [ "$ACTUAL" != "$EXPECTED" ]; then
    die "checksum mismatch: expected $EXPECTED, got $ACTUAL"
  fi
  info "checksum verified"
}

# ── Version resolution ──

resolve_version() {
  if [ -n "$TAG" ]; then
    return
  fi
  info "resolving latest version..."
  TAG=$(download "https://api.github.com/repos/${REPO}/releases/latest" \
    | grep '"tag_name"' | head -1 | cut -d'"' -f4) \
    || die "failed to resolve latest version"
  if [ -z "$TAG" ]; then
    die "could not determine latest version"
  fi
  info "latest version: $TAG"
}

# ── Asset resolution ──

resolve_asset() {
  OS=$(detect_os)
  ARCH=$(detect_arch)
  LIBC=$(detect_libc)
  ASSET=""

  case "$OS/$ARCH" in
    linux/x86_64)
      if [ "$LIBC" = "gnu" ]; then
        ASSET="forjar-{version}-x86_64-unknown-linux-gnu.tar.gz"
      fi
      if [ "$LIBC" = "musl" ]; then
        ASSET="forjar-{version}-x86_64-unknown-linux-musl.tar.gz"
      fi
      [ -z "$ASSET" ] && ASSET="forjar-{version}-x86_64-unknown-linux-gnu.tar.gz"
      ;;
    linux/aarch64)
      if [ "$LIBC" = "gnu" ]; then
        ASSET="forjar-{version}-aarch64-unknown-linux-gnu.tar.gz"
      fi
      [ -z "$ASSET" ] && ASSET="forjar-{version}-aarch64-unknown-linux-gnu.tar.gz"
      ;;
    darwin/x86_64)
      ASSET="forjar-{version}-x86_64-apple-darwin.tar.gz"
      ;;
    darwin/aarch64)
      ASSET="forjar-{version}-aarch64-apple-darwin.tar.gz"
      ;;
    *) die "no pre-built binary for $OS/$ARCH" ;;
  esac

  if [ -z "$ASSET" ]; then
    die "no matching asset for $OS/$ARCH (libc=$LIBC)"
  fi

  # Expand {version} placeholder
  VERSION_NUM="${TAG#v}"
  ASSET=$(echo "$ASSET" | sed "s/{version}/$VERSION_NUM/g")
}

post_install() {
  echo "forjar installed successfully"
echo "Run 'forjar init' to get started"
}

# ── Main ──

main() {
  resolve_version
  resolve_asset

  ASSET_URL="https://github.com/${REPO}/releases/download/${TAG}/${ASSET}"
  TMPDIR=$(mktemp -d)
  ARCHIVE="$TMPDIR/$ASSET"
  trap 'rm -rf "$TMPDIR"' EXIT

  info "downloading $BINARY $TAG..."
  download_file "$ASSET_URL" "$ARCHIVE" || die "download failed: $ASSET_URL"

  verify_checksum

  info "extracting..."
  tar xzf "$ARCHIVE" -C "$TMPDIR" || die "extraction failed"

  # Determine install location
  DEST="${PREFIX:-$INSTALL_DIR}"
  if [ ! -w "$DEST" ] 2>/dev/null; then
    if [ -w "$FALLBACK_DIR" ] || mkdir -p "$FALLBACK_DIR" 2>/dev/null; then
      DEST="$FALLBACK_DIR"
      warn "$INSTALL_DIR not writable, installing to $DEST"
    else
      # Try with sudo
      info "$INSTALL_DIR not writable, using sudo..."
      sudo mkdir -p "$DEST" 2>/dev/null || die "cannot create $DEST"
      sudo cp "$TMPDIR/$BINARY" "$DEST/$BINARY" || die "install failed"
      sudo chmod +x "$DEST/$BINARY"
      info "installed $BINARY to $DEST/$BINARY"
      post_install
  info "verifying install..."
  if forjar --version >/dev/null 2>&1; then
    info "$(forjar --version)"
  else
    warn "version check failed -- binary may not be on PATH"
  fi
      return
    fi
  fi

  # Check existing binary
  if [ -f "$DEST/$BINARY" ] && [ "$FORCE" = "0" ]; then
    warn "$DEST/$BINARY already exists -- use --force to overwrite"
    return 1
  fi

  mkdir -p "$DEST" 2>/dev/null || true
  cp "$TMPDIR/$BINARY" "$DEST/$BINARY" || die "install failed"
  chmod +x "$DEST/$BINARY"
  info "installed $BINARY to $DEST/$BINARY"

  post_install
  info "verifying install..."
  if forjar --version >/dev/null 2>&1; then
    info "$(forjar --version)"
  else
    warn "version check failed -- binary may not be on PATH"
  fi

  # PATH hint
  case ":$PATH:" in
    *":$DEST:"*) ;;
    *) warn "add $DEST to your PATH: export PATH=\"$DEST:\$PATH\"" ;;
  esac
}

main
