#!/bin/bash
#
# Sentinel Package Manager - Installation Script
#
# Installs the tool user-wide for use across all repositories
#

set -e

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

# Installation directory (user-wide location)
INSTALL_DIR="${HOME}/.sentinel"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo -e "${BLUE}🛡️  Installing Sentinel Package Manager...${NC}"
echo ""

# Create installation directory structure
mkdir -p "$INSTALL_DIR"/{bin,lib,config}

# Copy files
echo -e "${BLUE}📦 Copying files...${NC}"
cp -r "$PROJECT_ROOT/lib" "$INSTALL_DIR/"
cp -r "$PROJECT_ROOT/bin" "$INSTALL_DIR/"
cp -r "$PROJECT_ROOT/config" "$INSTALL_DIR/"

# No dependencies to install - tool uses only Node.js built-ins

# Make wrapper script executable
chmod +x "$INSTALL_DIR/bin/sentinel.sh"

# Detect shell
SHELL_RC=""
if [ -f "$HOME/.zshrc" ]; then
  SHELL_RC="$HOME/.zshrc"
  SHELL_NAME="zsh"
elif [ -f "$HOME/.bashrc" ]; then
  SHELL_RC="$HOME/.bashrc"
  SHELL_NAME="bash"
elif [ -f "$HOME/.bash_profile" ]; then
  SHELL_RC="$HOME/.bash_profile"
  SHELL_NAME="bash"
else
  echo -e "${YELLOW}⚠️  Could not find shell RC file${NC}"
  exit 1
fi

# Add aliases
if grep -q "sentinel" "$SHELL_RC" 2>/dev/null; then
  echo -e "${YELLOW}⚠️  Aliases already exist in $SHELL_RC${NC}"
  echo -e "${YELLOW}   Updating aliases...${NC}"
  # Remove existing aliases and comment (for re-installation)
  sed -i.bak '/\.sentinel\/bin\/sentinel\.sh/d' "$SHELL_RC"
  sed -i.bak '/^# Sentinel Package Manager$/d' "$SHELL_RC"
fi

echo "" >> "$SHELL_RC"
echo "# Sentinel Package Manager" >> "$SHELL_RC"
echo "alias npm='$INSTALL_DIR/bin/sentinel.sh npm'" >> "$SHELL_RC"
echo "alias yarn='$INSTALL_DIR/bin/sentinel.sh yarn'" >> "$SHELL_RC"
echo "alias pnpm='$INSTALL_DIR/bin/sentinel.sh pnpm'" >> "$SHELL_RC"
echo "alias bun='$INSTALL_DIR/bin/sentinel.sh bun'" >> "$SHELL_RC"
echo -e "${GREEN}✅ Aliases added to $SHELL_RC${NC}"

echo ""
echo -e "${GREEN}✅ Installation Complete!${NC}"
echo ""
echo -e "${BLUE}📋 Next Steps:${NC}"
echo -e "  1. Reload your shell:"
echo -e "     ${YELLOW}source $SHELL_RC${NC}"
echo -e "     ${YELLOW}# or open a new terminal${NC}"
echo ""
echo -e "  2. Use package managers normally:"
echo -e "     ${YELLOW}npm install package-name${NC}"
echo -e "     ${YELLOW}yarn add package-name${NC}"
echo -e "     ${YELLOW}pnpm add package-name${NC}"
echo -e "     ${YELLOW}bun add package-name${NC}"
echo ""
echo -e "  3. Packages will be automatically validated before installation"
echo ""
echo -e "${BLUE}📁 Installation Location:${NC}"
echo -e "   ${YELLOW}$INSTALL_DIR${NC}"
echo ""
echo -e "${BLUE}🔄 To Update:${NC}"
echo -e "   Run this script again to update the tool and JSON file"
echo ""

