#!/usr/bin/env bash
set -euo pipefail

# Script Name: jshop
# Description: OWASP Juice Shop launcher
# Usage: jshop start|stop|status|logs

VERSION="1.0.0"

# Colors
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly CYAN='\033[0;36m'
readonly BOLD='\033[1m'
readonly NC='\033[0m'

CONTAINER_NAME="juice-shop"
IMAGE="bkimminich/juice-shop"
DEFAULT_PORT="3000"

# Find available port
find_available_port() {
  local port="${1:-3000}"
  while lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1 || sudo netstat -tuln | grep -q ":$port "; do
    echo -e "${YELLOW}⚠${NC} Port $port in use, trying next..." >&2
    port=$((port + 1))
  done
  echo "$port"
}

show_help() {
  echo -e "${BOLD}jshop${NC} - OWASP Juice Shop Launcher v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  jshop <command>"
  echo
  echo -e "${BOLD}COMMANDS:${NC}"
  echo -e "  ${CYAN}start${NC}      Start Juice Shop"
  echo -e "  ${CYAN}stop${NC}       Stop Juice Shop"
  echo -e "  ${CYAN}restart${NC}    Restart Juice Shop"
  echo -e "  ${CYAN}status${NC}     Check if running"
  echo -e "  ${CYAN}logs${NC}       Show container logs"
  echo -e "  ${CYAN}shell${NC}      Open shell in container"
  echo
  echo -e "${BOLD}EXAMPLES:${NC}"
  echo "  jshop start    # Launch Juice Shop"
  echo "  jshop stop     # Stop Juice Shop"
  echo "  jshop logs     # View logs"
  echo
  echo -e "${BOLD}ACCESS:${NC}"
  echo "  URL: ${BOLD}http://localhost:\$PORT${NC} (auto-detects available port)"
  echo
  echo -e "${BOLD}ABOUT:${NC}"
  echo "  OWASP Juice Shop - Intentionally insecure web application"
  echo "  Perfect for testing: XSS, SQLi, auth bypass, IDOR, etc."
  echo "  Docs: https://pwning.owasp-juice.shop/"
}

check_docker() {
  if ! command -v docker &>/dev/null; then
    echo -e "${RED}Error:${NC} Docker not installed"
    exit 1
  fi
}

start_jshop() {
  # Find available port only when starting
  PORT=$(find_available_port "$DEFAULT_PORT")

  if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
      echo -e "${YELLOW}⚠${NC} Juice Shop already running"
      CURRENT_PORT=$(docker port "$CONTAINER_NAME" 3000 | cut -d: -f2)
      echo -e "${CYAN}[*]${NC} Access at: ${BOLD}http://localhost:${CURRENT_PORT}${NC}"
      return 0
    else
      echo -e "${CYAN}[*]${NC} Starting existing container..."
      docker start "$CONTAINER_NAME"
    fi
  else
    echo -e "${CYAN}[*]${NC} Pulling ${IMAGE}..."
    docker pull "$IMAGE"
    echo -e "${CYAN}[*]${NC} Starting Juice Shop..."
    docker run -d --name "$CONTAINER_NAME" -p "${PORT}:3000" "$IMAGE"
  fi

  echo -e "${GREEN}✓${NC} Juice Shop started"
  if [[ "$PORT" != "$DEFAULT_PORT" ]]; then
    echo -e "${YELLOW}⚠${NC} Using port ${PORT} (default ${DEFAULT_PORT} was in use)"
  fi
  echo -e "${CYAN}[*]${NC} Access at: ${BOLD}http://localhost:${PORT}${NC}"
}

stop_jshop() {
  if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${CYAN}[*]${NC} Stopping Juice Shop..."
    docker stop "$CONTAINER_NAME"
    echo -e "${GREEN}✓${NC} Juice Shop stopped"
  else
    echo -e "${YELLOW}⚠${NC} Juice Shop not running"
  fi
}

restart_jshop() {
  stop_jshop
  sleep 2
  start_jshop
}

show_status() {
  if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${GREEN}●${NC} Juice Shop is ${GREEN}running${NC}"
    CURRENT_PORT=$(docker port "$CONTAINER_NAME" 3000 2>/dev/null | cut -d: -f2)
    echo -e "${CYAN}[*]${NC} Access at: ${BOLD}http://localhost:${CURRENT_PORT}${NC}"
    docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -E "(NAMES|${CONTAINER_NAME})"
  else
    echo -e "${RED}●${NC} Juice Shop is ${RED}stopped${NC}"
  fi
}

show_logs() {
  if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    docker logs -f "$CONTAINER_NAME"
  else
    echo -e "${RED}Error:${NC} Juice Shop not running"
    exit 1
  fi
}

open_shell() {
  if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    docker exec -it "$CONTAINER_NAME" /bin/sh
  else
    echo -e "${RED}Error:${NC} Juice Shop not running"
    exit 1
  fi
}

# Main
check_docker

if [[ $# -eq 0 ]] || [[ "$1" =~ ^(-h|--help|help)$ ]]; then
  show_help
  exit 0
fi

case "$1" in
  start|up)
    start_jshop
    ;;
  stop|down)
    stop_jshop
    ;;
  restart)
    restart_jshop
    ;;
  status)
    show_status
    ;;
  logs)
    show_logs
    ;;
  shell|sh|bash)
    open_shell
    ;;
  *)
    echo -e "${RED}Error:${NC} Unknown command: $1"
    echo "Run 'jshop --help' for usage"
    exit 1
    ;;
esac
