#!/bin/bash
# Install script for registry-tools
# Usage: curl -fsSL https://get.tool.ab0t.com/p/registry-tools/meta/install.sh | bash
#    or: curl -fsSL https://get.tool.ab0t.com/p/registry-tools/meta/install.sh | bash -s -- --version 0.1.0

set -euo pipefail

# Defaults
INSTALL_DIR="${HOME}/.ab0t-registry"
BASE_URL="https://get.tool.ab0t.com/p/registry-tools"
VERSION="latest"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info()    { echo -e "${BLUE}info:${NC} $*"; }
success() { echo -e "${GREEN}success:${NC} $*"; }
warn()    { echo -e "${YELLOW}warning:${NC} $*"; }
error()   { echo -e "${RED}error:${NC} $*"; exit 1; }

usage() {
  cat << 'EOF'
registry-tools installer

Usage:
  curl -fsSL https://get.tool.ab0t.com/p/registry-tools/meta/install.sh | bash
  curl -fsSL https://get.tool.ab0t.com/p/registry-tools/meta/install.sh | bash -s -- [OPTIONS]

Options:
  --version VER   Install specific version (default: latest)
  --dir PATH      Install to custom directory (default: ~/.ab0t-registry)
  --help          Show this help message

Examples:
  # Install latest
  curl -fsSL https://get.tool.ab0t.com/p/registry-tools/meta/install.sh | bash

  # Install specific version
  curl -fsSL .../install.sh | bash -s -- --version 0.1.0

  # Custom directory
  curl -fsSL .../install.sh | bash -s -- --dir /opt/registry

What gets installed:
  - common.sh         Shared utilities
  - new-package.sh    Create new packages
  - publish.sh        Publish versions
  - tag.sh            Manage tags
  - delete.sh         Delete versions (with safeguards)
  - list.sh           List packages/versions

Requirements:
  - bash 4.0+
  - jq (JSON processor)
  - curl or wget
EOF
}

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --version|-v)
      VERSION="$2"
      shift 2
      ;;
    --dir|-d)
      INSTALL_DIR="$2"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      error "Unknown option: $1 (use --help for usage)"
      ;;
  esac
done

echo ""
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   registry-tools installer             ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
echo ""

# Check requirements
info "Checking requirements..."

if ! command -v jq &> /dev/null; then
  error "jq is required but not installed.

Install with:
  Ubuntu/Debian: sudo apt install jq
  macOS:         brew install jq
  Alpine:        apk add jq"
fi

if ! command -v curl &> /dev/null && ! command -v wget &> /dev/null; then
  error "curl or wget is required but neither is installed"
fi

# Determine download command
if command -v curl &> /dev/null; then
  download() { curl -fsSL "$1"; }
else
  download() { wget -qO- "$1"; }
fi

success "Requirements met (jq: $(jq --version))"

# Resolve version
if [ "$VERSION" = "latest" ]; then
  info "Resolving latest version..."
  RESOLVED_VERSION=$(download "${BASE_URL}/meta.json" | jq -r '.tags.latest')
  if [ -z "$RESOLVED_VERSION" ] || [ "$RESOLVED_VERSION" = "null" ]; then
    error "Could not resolve latest version"
  fi
  VERSION="$RESOLVED_VERSION"
fi

info "Installing version: $VERSION"
info "Install directory: $INSTALL_DIR"

# Create install directory
mkdir -p "$INSTALL_DIR"

# Download scripts
SCRIPTS="common.sh new-package.sh publish.sh tag.sh delete.sh list.sh"
DOWNLOAD_URL="${BASE_URL}/@${VERSION}"

for script in $SCRIPTS; do
  info "Downloading $script..."
  if ! download "${DOWNLOAD_URL}/${script}" > "${INSTALL_DIR}/${script}"; then
    error "Failed to download $script"
  fi
  chmod +x "${INSTALL_DIR}/${script}"
done

success "Scripts installed!"

# Verify installation
info "Verifying installation..."
if "${INSTALL_DIR}/list.sh" --help > /dev/null 2>&1; then
  success "Installation verified"
else
  warn "Installation may have issues - please check manually"
fi

# Save version info
echo "$VERSION" > "${INSTALL_DIR}/.version"

echo ""
echo -e "${GREEN}Installation complete!${NC}"
echo ""
echo "  Version:   $VERSION"
echo "  Location:  $INSTALL_DIR"
echo ""
echo "To add to your PATH, add this to ~/.bashrc or ~/.zshrc:"
echo ""
echo -e "  ${YELLOW}export PATH=\"${INSTALL_DIR}:\$PATH\"${NC}"
echo ""
echo "Or run scripts directly:"
echo ""
echo "  ${INSTALL_DIR}/list.sh --help"
echo "  ${INSTALL_DIR}/new-package.sh my-lib \"My library\""
echo ""
