import android.content.AttributionSource;
import android.net.wifi.WifiConfiguration;
import android.os.Bundle;
import android.os.IBinder;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * esTV WiFi owner fix - run on the device as the adb shell user:
 *   CLASSPATH=/data/local/tmp/wifiownerfix.dex app_process / WifiOwnerFix <list|selftest|fix> [creatorName]
 *
 * Android deletes every saved WiFi network created by an app when that app is
 * disabled. Google TV saves the network from the setup wizard
 * (com.google.android.tungsten.setupwraith), so disabling setupwraith wipes it.
 * "fix" re-saves those networks under the shell uid (2000) so they survive.
 * Passwords are never printed.
 */
public class WifiOwnerFix {
    private static final String PKG = "com.android.shell";
    private static final String DEFAULT_CREATOR = "com.google.android.tungsten.setupwraith";
    private static final String TEST_SSID = "\"ESTV_OWNER_SELFTEST\"";

    private static Object wifi;

    public static void main(String[] args) {
        String mode = args.length > 0 ? args[0] : "list";
        String creator = args.length > 1 ? args[1] : DEFAULT_CREATOR;
        try {
            Object binder = Class.forName("android.os.ServiceManager")
                    .getMethod("getService", String.class).invoke(null, "wifi");
            wifi = Class.forName("android.net.wifi.IWifiManager$Stub")
                    .getMethod("asInterface", IBinder.class).invoke(null, binder);
            switch (mode) {
                case "list": list(); break;
                case "selftest": System.exit(selftest() ? 0 : 1); break;
                case "fix": System.exit(fix(creator)); break;
                default:
                    System.out.println("usage: WifiOwnerFix <list|selftest|fix> [creatorName]");
                    System.exit(2);
            }
        } catch (Throwable t) {
            System.out.println("RESULT=ERROR " + rootCause(t));
            System.exit(3);
        }
    }

    // ---------------------------------------------------------------- modes

    private static void list() throws Exception {
        for (WifiConfiguration c : networks()) {
            System.out.println("netId=" + c.networkId + " ssid=" + c.SSID
                    + " creator=" + creatorName(c) + " (uid " + creatorUid(c) + ")"
                    + " hasPassword=" + (c.preSharedKey != null && !c.preSharedKey.isEmpty()));
        }
    }

    private static boolean selftest() throws Exception {
        WifiConfiguration t = new WifiConfiguration();
        t.SSID = TEST_SSID;
        t.preSharedKey = "\"selftest123\"";
        t.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
        int id = add(t);
        if (id < 0) {
            System.out.println("RESULT=FAIL addOrUpdateNetwork returned " + id);
            return false;
        }
        boolean ok = false;
        for (WifiConfiguration c : networks()) {
            if (c.networkId == id) {
                System.out.println("test network netId=" + id + " creator=" + creatorName(c) + " (uid " + creatorUid(c) + ")");
                ok = creatorUid(c) == 2000;
            }
        }
        remove(id);
        System.out.println(ok ? "RESULT=OK" : "RESULT=FAIL test network not owned by shell");
        return ok;
    }

    /** @return 0 = fixed or nothing to fix, 1 = a network could not be re-saved */
    private static int fix(String creator) throws Exception {
        List<WifiConfiguration> targets = new ArrayList<>();
        for (WifiConfiguration c : networks()) {
            if (creator.equals(creatorName(c))) targets.add(c);
        }
        if (targets.isEmpty()) {
            System.out.println("RESULT=NOTHING_TO_FIX no saved network created by " + creator);
            return 0;
        }

        int failures = 0;
        for (WifiConfiguration old : targets) {
            int oldId = old.networkId;
            System.out.println("re-saving netId=" + oldId + " ssid=" + old.SSID);

            // The same SSID+security can only be saved once, and an update keeps
            // the original creator - so the old entry must be removed first.
            if (!remove(oldId)) {
                System.out.println("  removeNetwork failed, left unchanged");
                failures++;
                continue;
            }

            old.networkId = -1;
            int newId = add(old);
            if (newId < 0) newId = add(rebuild(old));
            if (newId < 0) {
                System.out.println("  FAILED to re-save " + old.SSID + " - re-enter the WiFi password on the device");
                failures++;
                continue;
            }
            System.out.println("  saved as netId=" + newId);
            enable(newId);
        }

        // Verify ownership.
        for (WifiConfiguration c : networks()) {
            if (creator.equals(creatorName(c))) failures++;
        }
        System.out.println(failures == 0 ? "RESULT=OK" : "RESULT=FAIL " + failures + " network(s) not re-saved");
        return failures == 0 ? 0 : 1;
    }

    // ------------------------------------------------------- wifi service calls

    @SuppressWarnings("unchecked")
    private static List<WifiConfiguration> networks() throws Exception {
        Object slice = method("getPrivilegedConfiguredNetworks").invoke(wifi, PKG, null, extras());
        List<WifiConfiguration> result = new ArrayList<>();
        if (slice == null) return result;
        // One entry is returned per security type (e.g. WPA2 + WPA3 upgrade) - keep one per netId.
        java.util.Set<Integer> seen = new java.util.HashSet<>();
        for (WifiConfiguration c : (List<WifiConfiguration>) slice.getClass().getMethod("getList").invoke(slice)) {
            if (seen.add(c.networkId)) result.add(c);
        }
        return result;
    }

    private static int add(WifiConfiguration c) {
        try {
            return (Integer) method("addOrUpdateNetwork").invoke(wifi, c, PKG, extras());
        } catch (Throwable t) {
            System.out.println("  addOrUpdateNetwork error: " + rootCause(t));
            return -1;
        }
    }

    private static boolean remove(int netId) {
        try {
            return (Boolean) method("removeNetwork").invoke(wifi, netId, PKG);
        } catch (Throwable t) {
            System.out.println("  removeNetwork error: " + rootCause(t));
            return false;
        }
    }

    private static void enable(int netId) {
        try {
            method("enableNetwork").invoke(wifi, netId, true, PKG);
            method("reconnect").invoke(wifi, PKG);
        } catch (Throwable t) {
            System.out.println("  reconnect error (network is saved, it will auto-join): " + rootCause(t));
        }
    }

    // --------------------------------------------------------------- helpers

    /** Minimal copy for when the system rejects the full config object. */
    private static WifiConfiguration rebuild(WifiConfiguration old) {
        WifiConfiguration c = new WifiConfiguration();
        c.SSID = old.SSID;
        c.hiddenSSID = old.hiddenSSID;
        if (old.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SAE)
                && !old.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
            c.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
            c.preSharedKey = old.preSharedKey;
        } else if (old.preSharedKey != null && !old.preSharedKey.isEmpty()) {
            c.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
            c.preSharedKey = old.preSharedKey;
        } else {
            c.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
        }
        return c;
    }

    private static String creatorName(WifiConfiguration c) {
        try { return (String) WifiConfiguration.class.getField("creatorName").get(c); }
        catch (ReflectiveOperationException e) { return null; }
    }

    private static int creatorUid(WifiConfiguration c) {
        try { return WifiConfiguration.class.getField("creatorUid").getInt(c); }
        catch (ReflectiveOperationException e) { return -1; }
    }

    private static Bundle extras() {
        Bundle b = new Bundle();
        b.putParcelable("EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE",
                new AttributionSource.Builder(2000).setPackageName(PKG).build());
        return b;
    }

    private static Method method(String name) {
        for (Method m : wifi.getClass().getMethods()) {
            if (m.getName().equals(name)) return m;
        }
        throw new IllegalStateException("IWifiManager." + name + " not found");
    }

    private static String rootCause(Throwable t) {
        while (t.getCause() != null) t = t.getCause();
        return t.toString();
    }
}
