import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.Security;
import java.util.concurrent.TimeUnit;

public class DnsCacheBoundaryDemo {
    public static void main(String[] args) throws Exception {
        if (args.length == 3 && args[0].equals("worker")) {
            observe(args[1], Path.of(args[2]));
            return;
        }
        if (args.length != 1 || (!args[0].equals("0") && !args[0].equals("-1"))) {
            throw new IllegalArgumentException("use a fresh JVM: DnsCacheBoundaryDemo <0|-1>");
        }
        String ttl = args[0];
        Path hosts = Files.createTempFile("kb-dns-cache-", ".hosts");
        try {
            Files.writeString(hosts, "192.0.2.10 positive.kb.test\n", StandardCharsets.UTF_8);
            String executable = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
            Process worker = new ProcessBuilder(
                    Path.of(System.getProperty("java.home"), "bin", executable).toString(),
                    "-Djdk.net.hosts.file=" + hosts.toAbsolutePath(),
                    "-cp", System.getProperty("java.class.path"),
                    DnsCacheBoundaryDemo.class.getName(), "worker", ttl, hosts.toAbsolutePath().toString())
                    .inheritIO().start();
            try {
                if (!worker.waitFor(20, TimeUnit.SECONDS)) throw new IllegalStateException("worker timeout");
                if (worker.exitValue() != 0) throw new IllegalStateException("worker failed");
            } finally {
                if (worker.isAlive()) {
                    worker.destroyForcibly();
                    worker.waitFor();
                }
            }
        } finally {
            Files.deleteIfExists(hosts);
        }
    }

    private static void observe(String ttl, Path hosts) throws Exception {
        Security.setProperty("networkaddress.cache.ttl", ttl);
        Security.setProperty("networkaddress.cache.negative.ttl", ttl);
        System.out.println("jdk=" + System.getProperty("java.runtime.version") + " positiveTTL="
                + Security.getProperty("networkaddress.cache.ttl") + " negativeTTL="
                + Security.getProperty("networkaddress.cache.negative.ttl"));
        String before = InetAddress.getByName("positive.kb.test").getHostAddress();
        if (!before.equals("192.0.2.10")) throw new IllegalStateException("isolated hosts not applied");
        expectMissing("negative.kb.test");
        Files.writeString(hosts, "192.0.2.20 positive.kb.test\n192.0.2.30 negative.kb.test\n", StandardCharsets.UTF_8);
        String after = InetAddress.getByName("positive.kb.test").getHostAddress();
        if (ttl.equals("-1")) {
            if (!after.equals(before)) throw new IllegalStateException("positive cache not retained");
            expectMissing("negative.kb.test");
            System.out.println("hosts changed; positive remains=" + after + "; negative remains missing: PASS");
        } else {
            if (!after.equals("192.0.2.20")) throw new IllegalStateException("positive not refreshed");
            String newlyAdded = InetAddress.getByName("negative.kb.test").getHostAddress();
            if (!newlyAdded.equals("192.0.2.30")) throw new IllegalStateException("negative not refreshed");
            System.out.println("hosts changed; positive refreshed=" + after + "; negative refreshed=" + newlyAdded + ": PASS");
        }
    }

    private static void expectMissing(String name) throws Exception {
        try {
            InetAddress.getByName(name);
            throw new IllegalStateException("expected UnknownHostException");
        } catch (UnknownHostException expected) {
            System.out.println("lookup missing=" + name);
        }
    }
}
