#!/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-hour 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

# --- Root tasks: packages that need sudo ---
sudo apt-get update
# Install Chrome so headless browser is present (repo already configured on your box)
sudo apt-get install -y google-chrome-stable
# Python venv tooling
sudo apt-get install -y python3-venv python3-full

# Ensure 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/overwrite the Python script
  cat > \"$SCRIPT_DIR/$PYTHON_SCRIPT\" << 'PYEOF'
#!/usr/bin/env python3
import os, time, random, glob
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.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions

USERNAME = os.environ.get('APRS_USERNAME')  # set in ~bbl/.bashrc
PASSWORD = os.environ.get('APRS_PASSWORD')  # set in ~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.6, b=1.6):
    import random, time
    time.sleep(random.uniform(a, b))

# Headless Chrome with auto-download
chrome_prefs = {
    'download.default_directory': OUTPUT_DIR,
    'download.prompt_for_download': False,
    'profile.default_content_setting_values.automatic_downloads': 1,
    'safebrowsing.enabled': True,
}
options = ChromeOptions()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_experimental_option('prefs', chrome_prefs)

driver = webdriver.Chrome(
    service=ChromeService(ChromeDriverManager().install()),
    options=options
)
wait = WebDriverWait(driver, 25)

# Allow downloads in headless via CDP (belt-and-suspenders)
try:
    driver.execute_cdp_cmd('Page.setDownloadBehavior', {
        'behavior': 'allow',
        'downloadPath': OUTPUT_DIR
    })
except Exception:
    pass

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()

    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.5)
    pw.clear(); pw.send_keys(PASSWORD or '')
    pw.send_keys(Keys.RETURN)
    human_delay()

    # Export page (positions export)
    driver.get('https://aprs.fi/export/')
    human_delay()

    # Fill fields
    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)

    # Prefer CSV if there’s a format radio
    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

    # Submit export
    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.0, 3.5)

    # Wait for download to appear (simple polling)
    deadline = time.time() + 20
    before = set(glob.glob(os.path.join(OUTPUT_DIR, '*')))
    downloaded = None
    while time.time() < deadline:
        time.sleep(1)
        after = set(glob.glob(os.path.join(OUTPUT_DIR, '*')))
        new_files = list(after - before)
        if new_files:
            # Ignore .crdownload temp files
            candidates = [f for f in new_files if not f.endswith('.crdownload')]
            if candidates:
                downloaded = sorted(candidates, key=os.path.getmtime)[-1]
                break

    if downloaded:
        dest = os.path.join(OUTPUT_DIR, OUTPUT_FILE)
        if downloaded != dest:
            try:
                os.replace(downloaded, dest)
                print('Saved', dest)
            except Exception as e:
                print('Downloaded but rename failed:', e, downloaded)
        else:
            print('Saved', dest)
    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\"

  # Run with env
  export OUTPUT_DIR=\"$OUTPUT_DIR\"
  export CALLSIGN=\"$CALLSIGN\"
  export START_TIME=\"$START_TIME\"
  export END_TIME=\"$END_TIME\"
  export OUTPUT_FILE=\"$OUTPUT_FILE\"

  echo \"Running export at \$(date -u) ...\"
  \"$VENV_DIR/bin/python\" \"$SCRIPT_DIR/$PYTHON_SCRIPT\"
"

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