#!/bin/bash

# Clean up all Docker containers and homepage Flask processes for the given instance IDs.
# Usage: ./clean_containers.sh <instance_id1> [instance_id2 ...]

set -o pipefail

show_usage() {
  echo "Usage: $0 <instance_id1> [instance_id2 ...]"
  echo "  Deletes Docker containers whose names end with -<ID> or _<ID>."
  echo "  Also kills homepage Flask processes started as: app.py <ID> --port <PORT>."
  exit 1
}

is_numeric() {
  [[ "$1" =~ ^[0-9]+$ ]]
}

kill_flask_processes_for_id() {
  local id="$1"
  local pattern="app\\.py ${id} --port"
  # Find and kill matching Flask processes if any
  local pids
  pids=$(pgrep -f "$pattern" || true)
  if [[ -n "$pids" ]]; then
    echo "Killing homepage Flask processes for ID $id: $pids"
    # shellcheck disable=SC2086
    kill $pids 2>/dev/null || true
    # Give them a moment to exit, then force kill if needed
    sleep 0.5
    # shellcheck disable=SC2046
    if [[ -n $(pgrep -f "$pattern" || true) ]]; then
      echo "Forcing kill for remaining Flask processes for ID $id"
      pkill -9 -f "$pattern" 2>/dev/null || true
    fi
  else
    echo "No homepage Flask processes found for ID $id"
  fi
}

remove_containers_for_id() {
  local id="$1"

  # Match names that have -ID- or _ID- (or start/end with it), not just at the end.
  local containers
  containers=$(docker ps -a --format '{{.Names}}' | grep -E '(^|[-_])'"${id}"'([-_]|$)' || true)

  if [[ -z "$containers" ]]; then
    echo "No Docker containers found for ID $id"
  else
    echo "Removing Docker containers for ID $id:"
    while IFS= read -r name; do
      [[ -z "$name" ]] && continue
      echo "  - $name"
      
      # Get volumes used by this container before removing it
      local volumes
      volumes=$(docker inspect "$name" --format '{{range .Mounts}}{{.Name}}{{end}}' 2>/dev/null | tr -d '\n' || true)
      
      # Remove the container
      docker rm -f "$name" || true
      
      # Remove associated volumes if any
      if [[ -n "$volumes" ]]; then
        echo "    Removing volumes: $volumes"
        echo "$volumes" | tr ' ' '\n' | while IFS= read -r volume; do
          [[ -z "$volume" ]] && continue
          docker volume rm "$volume" 2>/dev/null || echo "    Warning: Could not remove volume $volume"
        done
      fi

    done <<< "$containers"
  fi
}

main() {
  if [[ $# -eq 0 ]]; then
    show_usage
  fi

  for id in "$@"; do
    if ! is_numeric "$id"; then
      echo "Skipping invalid instance ID: $id (must be numeric)" >&2
      continue
    fi

    echo "\n=== Cleaning resources for instance ID: $id ==="
    remove_containers_for_id "$id"
    kill_flask_processes_for_id "$id"
  done

  echo "\nCleanup complete."
}

main "$@"
