#!/usr/bin/env python3
"""
SolarmanPV WiFi Logger Provisioner
Connects to inverter AP (130000251257777051) and configures it to join AhoySmartHome

The SolarmanPV logger (LSW-3, S3-WiFi etc) has:
- AP mode SSID: serial number
- Default AP password: 12345678 (or open)
- Web portal: http://10.10.100.254
- Provisioning endpoint: POST to /page/wifisetup.cgi or similar
"""
import requests
import subprocess
import time
import sys

INVERTER_SSID = "130000251257777051"
INVERTER_AP_PASS = "12345678"  # common default
INVERTER_AP_IP = "10.10.100.254"
TARGET_SSID = "AhoySmartHome"
TARGET_PASS = "106granada"

def try_connect_to_inverter():
    """Try connecting to inverter AP"""
    print(f"[*] Scanning for {INVERTER_SSID}...")
    result = subprocess.run(['nmcli', 'dev', 'wifi', 'list'], capture_output=True, text=True)
    if INVERTER_SSID in result.stdout:
        print(f"[+] Found {INVERTER_SSID}!")
        return True
    print(f"[-] {INVERTER_SSID} not visible from fred")
    return False

def probe_inverter_webui(ip="10.10.100.254"):
    """Try to reach inverter web UI"""
    urls = [
        f"http://{ip}/",
        f"http://{ip}/index.html",
        f"http://{ip}/page/index.html",
    ]
    for url in urls:
        try:
            r = requests.get(url, timeout=5)
            print(f"[+] Got response from {url}: {r.status_code}")
            print(r.text[:500])
            return True
        except Exception as e:
            print(f"[-] {url}: {e}")
    return False

def try_solarman_provision(ip="10.10.100.254"):
    """Try various SolarmanPV provisioning endpoints"""
    endpoints = [
        ("/page/wifisetup.cgi", {"ssid": TARGET_SSID, "password": TARGET_PASS}),
        ("/wifi/config", {"ssid": TARGET_SSID, "psk": TARGET_PASS}),
        ("/cgi-bin/set_wifi.cgi", {"ssid": TARGET_SSID, "pass": TARGET_PASS}),
        ("/setConfig", {"wifi_ssid": TARGET_SSID, "wifi_pass": TARGET_PASS}),
    ]
    for path, data in endpoints:
        url = f"http://{ip}{path}"
        try:
            r = requests.post(url, data=data, timeout=5)
            print(f"[+] POST {url}: {r.status_code} - {r.text[:200]}")
        except Exception as e:
            print(f"[-] POST {url}: {e}")
        try:
            r = requests.get(url, params=data, timeout=5)
            print(f"[+] GET {url}: {r.status_code} - {r.text[:200]}")
        except Exception as e:
            pass

if __name__ == "__main__":
    print("=== SolarmanPV Inverter Provisioner ===")
    print(f"Target SSID: {TARGET_SSID}")
    print(f"Inverter SSID: {INVERTER_SSID}")
    print()
    
    found = try_connect_to_inverter()
    
    print("\n[*] Probing inverter at 10.10.100.254 (if connected to its AP)...")
    probe_inverter_webui()
    
    print("\n[*] Trying provisioning endpoints...")
    try_solarman_provision()
