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

# Script Name: dvwa
# Description: Damn Vulnerable Web Application launcher
# Usage: dvwa 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="dvwa"
IMAGE="vulnerables/web-dvwa"
DEFAULT_PORT="8080"

# Find available port
find_available_port() {
  local port="${1:-8080}"
  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}dvwa${NC} - DVWA Launcher v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  dvwa <command>"
  echo
  echo -e "${BOLD}COMMANDS:${NC}"
  echo -e "  ${CYAN}start${NC}      Start DVWA"
  echo -e "  ${CYAN}stop${NC}       Stop DVWA"
  echo -e "  ${CYAN}restart${NC}    Restart DVWA"
  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 "  dvwa start     # Launch DVWA"
  echo "  dvwa stop      # Stop DVWA"
  echo "  dvwa logs      # View logs"
  echo
  echo -e "${BOLD}ACCESS:${NC}"
  echo "  URL:      ${BOLD}http://localhost:\$PORT${NC} (default: 8080, auto-detects if in use)"
  echo "  Username: ${BOLD}admin${NC}"
  echo "  Password: ${BOLD}password${NC}"
  echo
  echo -e "${BOLD}SETUP:${NC}"
  echo "  1. Navigate to http://localhost"
  echo "  2. Click 'Create / Reset Database' button"
  echo "  3. Login with admin/password"
  echo "  4. Set Security Level (low/medium/high/impossible)"
  echo
  echo -e "${BOLD}ABOUT:${NC}"
  echo "  DVWA - Damn Vulnerable Web Application"
  echo "  Perfect for testing: SQLi, XSS, CSRF, Command Injection, etc."
  echo "  Docs: https://github.com/digininja/DVWA"
}

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

start_dvwa() {
  # 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} DVWA already running"
      CURRENT_PORT=$(docker port "$CONTAINER_NAME" 80 2>/dev/null | 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 DVWA..."
    docker run -d --name "$CONTAINER_NAME" -p "${PORT}:80" "$IMAGE"
  fi

  echo -e "${GREEN}✓${NC} DVWA 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}"
  echo -e "${CYAN}[*]${NC} Login: ${BOLD}admin / password${NC}"
  echo
  echo -e "${YELLOW}Note:${NC} First time? Click 'Create / Reset Database' at the bottom"
}

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

restart_dvwa() {
  stop_dvwa
  sleep 2
  start_dvwa
}

show_status() {
  if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${GREEN}●${NC} DVWA is ${GREEN}running${NC}"
    CURRENT_PORT=$(docker port "$CONTAINER_NAME" 80 2>/dev/null | cut -d: -f2)
    echo -e "${CYAN}[*]${NC} Access at: ${BOLD}http://localhost:${CURRENT_PORT}${NC}"
    echo -e "${CYAN}[*]${NC} Login: ${BOLD}admin / password${NC}"
    docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -E "(NAMES|${CONTAINER_NAME})"
  else
    echo -e "${RED}●${NC} DVWA 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} DVWA not running"
    exit 1
  fi
}

open_shell() {
  if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    docker exec -it "$CONTAINER_NAME" /bin/bash
  else
    echo -e "${RED}Error:${NC} DVWA 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_dvwa
    ;;
  stop|down)
    stop_dvwa
    ;;
  restart)
    restart_dvwa
    ;;
  status)
    show_status
    ;;
  logs)
    show_logs
    ;;
  shell|sh|bash)
    open_shell
    ;;
  *)
    echo -e "${RED}Error:${NC} Unknown command: $1"
    echo "Run 'dvwa --help' for usage"
    exit 1
    ;;
esac
