#!/bin/bash

# Exit on error
set -e

# Variables
VENV_DIR="/var/www/html/w1hd.aprs.trek/venv"
SCRIPT_DIR="/var/www/html/w1hd.aprs.trek"
PYTHON_SCRIPT="export_w1hd9_raw.py"
OUTPUT_DIR="/var/www/html/w1hd.aprs.trek"
CALLSIGN="W1HD-9"
START_TIME=$(date -u -d "8 hours ago" +%Y-%m-%d\ %H:%M)
END_TIME=$(date -u +%Y-%m-%d\ %H:%M)
OUTPUT_FILE="w1hd9_raw_${START_TIME// /_}_${END_TIME//:/}.txt"

# Switch to bbl user
sudo -u bbl bash << 'EOF'
# Create virtual environment if it doesn't exist
if [ ! -d "$VENV_DIR" ]; then
    echo "Creating virtual environment..."
    python3 -m venv "$VENV_DIR"
fi

# Activate virtual environment
source "$VENV_DIR/bin/activate"

# Install selenium and webdriver-manager within the virtual environment
echo "Installing selenium and webdriver-manager..."
pip install selenium webdriver-manager

# Install Firefox for headless use
sudo apt install -y firefox

# Write Python script
cat > "$SCRIPT_DIR/$PYTHON_SCRIPT" << 'INNER_EOF'
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.service import Service as FirefoxService
from datetime import datetime, timedelta
import time
import random
import os

# Configuration (set via environment variables)
USERNAME = os.environ.get("APRS_USERNAME", "k1te@lupton.us")  # Default to your username
PASSWORD = os.environ.get("APRS_PASSWORD")  # Required, set in ~/.bashrc
OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "/var/www/html/w1hd.aprs.trek")
CALLSIGN = os.environ.get("CALLSIGN", "W1HD-9")

# Set time range (passed from bash)
START_TIME = os.environ.get("START_TIME")
END_TIME = os.environ.get("END_TIME")
TIME_RANGE = f"{START_TIME}-{END_TIME}"

# Fake human delays (in seconds)
def human_delay(min_delay=2, max_delay=5):
    time.sleep(random.uniform(min_delay, max_delay))

# Initialize Firefox driver with webdriver-manager in headless mode
options = webdriver.FirefoxOptions()
options.add_argument("--headless")  # Run without GUI
driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)
human_delay()

try:
    # Navigate to aprs.fi
    driver.get("https://aprs.fi/")
    human_delay()

    # Log in
    login_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//a[contains(text(), 'Login')]"))
    )
    login_button.click()
    human_delay()

    username_field = driver.find_element(By.ID, "username")
    password_field = driver.find_element(By.ID, "password")
    username_field.send_keys(USERNAME)
    human_delay(1, 3)  # Slower typing
    password_field.send_keys(PASSWORD)
    human_delay(1, 3)
    password_field.send_keys(Keys.RETURN)
    human_delay()

    # Search for W1HD-9
    search_box = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "searchbox"))
    )
    search_box.send_keys(CALLSIGN)
    human_delay(1, 2)
    search_box.send_keys(Keys.RETURN)
    human_delay()

    # Go to raw packets tab
    raw_tab = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//a[contains(text(), 'raw')]"))
    )
    raw_tab.click()
    human_delay()

    # Set time range (manual adjustment via date picker)
    print(f"[Manual Step] Set date range to {TIME_RANGE} in the raw tab filter.")
    print("[Manual Step] Download the CSV/JSON file manually after filtering.")
    human_delay()

    # Save the file (manual step due to download handling)
    print(f"[Manual Step] Save the downloaded file as {OUTPUT_DIR}/{OUTPUT_FILE}")
    human_delay()

except Exception as e:
    print(f"Error: {e}")
finally:
    human_delay()
    driver.quit()
INNER_EOF

# Make Python script executable
chmod +x "$SCRIPT_DIR/$PYTHON_SCRIPT"

# Run the script with environment variables
export OUTPUT_DIR="$OUTPUT_DIR"
export CALLSIGN="$CALLSIGN"
export START_TIME="$START_TIME"
export END_TIME="$END_TIME"
echo "Running export script at $(date)..."
"$VENV_DIR/bin/python3" "$SCRIPT_DIR/$PYTHON_SCRIPT"

# Deactivate virtual environment
deactivate
EOF

echo "Export complete. Check $OUTPUT_DIR/$OUTPUT_FILE after manual download."
