#!/bin/bash

source "constants/env_constants.sh"
# echo "URLS_DIR: $URLS_DIR"
# echo "URLS_FILE_TEMPLATE: $URLS_FILE_TEMPLATE"

SITE_NAMES=()

# Default values
# Help function
print_usage() {
    echo "Usage: $0 [-p process_id] [-s \"site1 site2 ...\"] [-f url_file]"
    echo "Options:"
    echo "  -p    Process ID - if only process ID is given, checks all sites for that ID"
    echo "  -s    Space-separated list of site names (e.g., \"shopping reddit wikipedia\")"
    echo "  -f    File containing URLs to check (format: 'site-name url' per line)"
    echo "  -h    Show this help message"
    exit 1
}

# Add -f to getopts
while getopts "p:s:f:h" opt; do
  case $opt in
    p)
      PROCESS_ID="$OPTARG"
      ;;
    s)
      # Convert space-separated string to array
      read -ra SITE_NAMES <<< "$OPTARG"
      ;;
    f)
      URLS_FILE="$OPTARG"
      ;;
    h)
      print_usage
      ;;
    *)
      print_usage
      ;;
  esac
done

# If no URLS_FILE provided, use default logic
if [[ -z $URLS_FILE ]]; then
    if [[ -n $PROCESS_ID ]]; then
        URLS_FILE="${URLS_FILE_TEMPLATE//\{PROCESS_ID\}/$PROCESS_ID}"
        # echo "URLS_FILE: $URLS_FILE"
    else
        URLS_FILE=$(mktemp)
        sort $URLS_DIR/*.txt | uniq > $URLS_FILE
    fi
fi


# Generate site identifiers based on process ID and site types
SITES_TO_CHECK=()
if [[ -n $PROCESS_ID ]]; then
    if [[ ${#SITE_NAMES[@]} -gt 0 ]]; then
        # If both process ID and site names are provided
        for site_name in "${SITE_NAMES[@]}"; do
            SITES_TO_CHECK+=("$site_name-$PROCESS_ID")
        done
    else
        # If only process ID is provided, we'll filter by ID in the loop
        echo "Checking all sites for process ID: $PROCESS_ID"
    fi
fi

if [[ ${#SITE_NAMES[@]} -gt 0 ]]; then
    echo "Checking sites: ${SITE_NAMES[*]}"
fi

check_url() {
    local url=$1
    # Try to connect with a 5 second timeout
    if curl -s -f --max-time 5 "$url" > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

while IFS= read -r line; do
    site=$(echo "$line" | cut -d ' ' -f 1)
    url=$(echo "$line" | cut -d ' ' -f 2)

    # If process ID is provided but no specific sites, filter by process ID
    if [[ -n $PROCESS_ID && ${#SITE_NAMES[@]} -eq 0 ]]; then
        if [[ ! "$site" =~ -$PROCESS_ID$ ]]; then
            continue
        fi
    fi

    # If specific sites were provided, filter by them (with or without process ID)
    if [[ ${#SITE_NAMES[@]} -gt 0 ]]; then
        match=false
        for s in "${SITE_NAMES[@]}"; do
            if [[ -n $PROCESS_ID ]]; then
                # Require exact match with process id
                if [[ "$site" == "$s-$PROCESS_ID" ]]; then
                    match=true
                    break
                fi
            else
                # Allow any process id
                if [[ "$site" == "$s" || "$site" == "$s-"* ]]; then
                    match=true
                    break
                fi
            fi
        done
        if ! $match; then
            continue
        fi
    fi

    if check_url "$url"; then
        printf "%-15s %-10s %s\n" "$site" "UP" "URL: $url"
    else
        printf "%-15s %-10s %s\n" "$site" "DOWN" "URL: $url"
    fi

done < "$URLS_FILE"
echo "Check complete."
