#!/bin/bash
set -euo pipefail

# --- Config ---
SCRIPT_DIR="/var/www/html/w1hd.aprs.trek"
VENV_DIR="$SCRIPT_DIR/venv"
PYTHON_SCRIPT="export_w1hd9_raw.py"
OUTPUT_DIR="$SCRIPT_DIR"
CALLSIGN="W1HD-9"

# 8 hours window in UTC
START_TIME=$(date -u -d "8 hours ago" +"%Y-%m-%d %H:%M")
END_TIME=$(date -u +"%Y-%m-%d %H:%M")

# sanitize both for filename
START_SAFE="${START_TIME//[: ]/_}"
END_SAFE="${END_TIME//[: ]/_}"
OUTPUT_FILE="w1hd9_raw_${START_SAFE}_${END_SAFE}.csv"   # choose CSV here

# --- Root tasks: packages that need sudo ---
if ! command -v python3 >/dev/null; then
  echo "python3 missing"
fi

sudo apt-get update
sudo apt-get install -y python3-venv python3-full firefox-esr geckodriver

# make sure the project dir exists and is owned by bbl
sudo mkdir -p "$SCRIPT_DIR"
sudo chown -R bbl:bbl "$SCRIPT_DIR"

# --- Switch to bbl for venv + pip + running python ---
sudo -u bbl -H bash -lc "
  set -euo pipefail

  # create venv if needed
  if [ ! -d \"$VENV_DIR\" ]; then
    echo 'Creating virtual environment...'
    python3 -m venv \"$VENV_DIR\"
  fi

  source \"$VENV_DIR/bin/activate\"

  python -m pip install --upgrade pip
  pip install --upgrade selenium webdriver-manager

  # write (or overwrite) the Python script
  cat > \"$SCRIPT_DIR/$PYTHON_SCRIPT\" << 'PYEOF'
#!/usr/bin/env python3
import os, time, random, json, sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.service import Service as FirefoxService

USERNAME = os.environ.get('APRS_USERNAME')  # put in /home/bbl/.bashrc
PASSWORD = os.environ.get('APRS_PASSWORD')  # put in /home/bbl/.bashrc
OUTPUT_DIR = os.environ.get('OUTPUT_DIR', '.')
CALLSIGN = os.environ.get('CALLSIGN', 'W1HD-9')
START_TIME = os.environ.get('START_TIME')   # 'YYYY-MM-DD HH:MM' UTC
END_TIME = os.environ.get('END_TIME')       # 'YYYY-MM-DD HH:MM' UTC
OUTPUT_FILE = os.environ.get('OUTPUT_FILE', 'export.csv')

def human_delay(a=0.7, b=1.8):
    time.sleep(random.uniform(a, b))

# Configure headless Firefox to auto-download CSV/JSON without dialogs
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.dir', OUTPUT_DIR)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv,application/json,application/octet-stream,text/plain')
profile.set_preference('pdfjs.disabled', True)

options = webdriver.FirefoxOptions()
options.add_argument('--headless')
driver = webdriver.Firefox(
    service=FirefoxService(GeckoDriverManager().install()),
    options=options,
    firefox_profile=profile
)

wait = WebDriverWait(driver, 20)

try:
    driver.get('https://aprs.fi/')
    human_delay()

    # Login
    login = wait.until(EC.element_to_be_clickable((By.XPATH, \"//a[contains(., 'Login')]\")))
    login.click()
    human_delay()

    # The exact IDs can vary; try common ones then fall back
    user = wait.until(EC.presence_of_element_located((By.XPATH, \"//*[@id='username' or @name='username' or @name='login']\")))
    pw   = wait.until(EC.presence_of_element_located((By.XPATH, \"//*[@id='password' or @name='password']\")))
    user.clear(); user.send_keys(USERNAME or '')
    human_delay(0.2, 0.6)
    pw.clear(); pw.send_keys(PASSWORD or '')
    pw.send_keys(Keys.RETURN)
    human_delay()

    # Go straight to the export page (positions export)
    driver.get('https://aprs.fi/export/')
    human_delay()

    # Fill callsign and date range (fields are typically named 'call', 'start', 'end')
    call_el  = wait.until(EC.presence_of_element_located((By.XPATH, \"//*[@name='call' or @id='call' or contains(@placeholder,'callsign')]\")))
    start_el = wait.until(EC.presence_of_element_located((By.XPATH, \"//*[@name='start' or @id='start']\")))
    end_el   = wait.until(EC.presence_of_element_located((By.XPATH, \"//*[@name='end' or @id='end']\")))

    call_el.clear();  call_el.send_keys(CALLSIGN)
    start_el.clear(); start_el.send_keys(START_TIME)
    end_el.clear();   end_el.send_keys(END_TIME)

    # Select CSV if there is a format chooser
    try:
        fmt_csv = driver.find_elements(By.XPATH, \"//input[@type='radio' and (contains(@value,'csv') or contains(@id,'csv'))]\")
        if fmt_csv:
            fmt_csv[0].click()
    except Exception:
        pass

    # Click Export / Submit
    export_btn = wait.until(EC.element_to_be_clickable((By.XPATH, \"//button[contains(.,'Export') or contains(.,'Download') or @type='submit']\")))
    export_btn.click()
    human_delay(2, 3.5)

    # Give downloads time to finish (crude but effective)
    time.sleep(5)

    # Rename the most recent download in the folder to our OUTPUT_FILE if needed
    import glob, os
    files = sorted(glob.glob(os.path.join(OUTPUT_DIR, '*')), key=os.path.getmtime)
    if files:
        newest = files[-1]
        dest = os.path.join(OUTPUT_DIR, OUTPUT_FILE)
        if newest != dest:
            try:
                os.replace(newest, dest)
                print('Saved', dest)
            except Exception as e:
                print('Download finished but rename failed:', e, newest)
    else:
        print('No file appeared in', OUTPUT_DIR)

except Exception as e:
    print('Error:', e)
finally:
    driver.quit()
PYEOF

  chmod +x \"$SCRIPT_DIR/$PYTHON_SCRIPT\"

  # export env and run
  export OUTPUT_DIR=\"$OUTPUT_DIR\"
  export CALLSIGN=\"$CALLSIGN\"
  export START_TIME=\"$START_TIME\"
  export END_TIME=\"$END_TIME\"
  export OUTPUT_FILE=\"$OUTPUT_FILE\"

  # Expect APRS_USERNAME/APRS_PASSWORD already in bbl's env (~/.bashrc)
  echo \"Running export at \$(date -u) ...\"
  \"$VENV_DIR/bin/python\" \"$SCRIPT_DIR/$PYTHON_SCRIPT\"
"

echo "Done. Check: $OUTPUT_DIR/$OUTPUT_FILE"
