#!/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"
USERNAME="your_aprs_fi_username"  # Replace with your aprs.fi username
PASSWORD="your_aprs_fi_password"  # Replace with your aprs.fi password
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"

# Create virtual environment if it doesn't exist
if [ ! -d "$VENV_DIR" ]; then
    echo "Creating virtual environment..."
    sudo apt install -y python3-venv
    python3 -m venv "$VENV_DIR"
fi

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

# Install selenium and dependencies
echo "Installing selenium..."
pip install selenium
sudo apt install -y firefox-geckodriver firefox

# Write Python script
cat > "$SCRIPT_DIR/$PYTHON_SCRIPT" << '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 datetime import datetime, timedelta
import time
import random
import os

# Configuration (set via bash script)
USERNAME = os.environ.get("APRS_USERNAME")
PASSWORD = os.environ.get("APRS_PASSWORD")
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
driver = webdriver.Firefox()
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()
EOF

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

# Run the script with environment variables
export APRS_USERNAME="$USERNAME"
export APRS_PASSWORD="$PASSWORD"
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

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