import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.CharBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

public final class PropertiesToResources {
    private static final String JDK_8339280 =
            "bbd5b174c50346152a624317b6bd76ec48f7e551";
    private static final Path RESOURCES_DIR = Path.of(
            "src", "jdk.jartool", "share", "classes",
            "sun", "security", "tools", "jarsigner", "resources");

    private static final String escape(String text) {
        StringBuilder sb = new StringBuilder(text.length());
        CharBuffer cb = CharBuffer.wrap(text);
        while (cb.hasRemaining()) {
            char c = cb.get();
            if (c == '\\') {
                sb.append('\\');
            }
            if (Character.UnicodeBlock.of(c) ==
                    Character.UnicodeBlock.BASIC_LATIN) {
                sb.append(c);
            } else {
                sb.append("\\u%04X".formatted((int) c));
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        // Get a list of added properties in the JDK-8339280 commit
        Path path = RESOURCES_DIR.resolve("jarsigner.properties");
        if (!Files.isRegularFile(path)) {
            System.err.println("Please run with CWD at a jdk repo clone");
            return;
        }
        List<String> propNames;
        try (BufferedReader br = new ProcessBuilder("git", "show", JDK_8339280,
                "--", path.toString()).start().inputReader()) {
            propNames = br.lines()
                    .filter(l -> l.startsWith("+") && !l.startsWith("++"))
                    .map(l -> l.split("^\\+|=")[1]).toList();
        }
        if (propNames.isEmpty()) {
            System.err.println("Please run at a jdk repo with JDK-8339280 " +
                    "(commit " + JDK_8339280 + ")");
            return;
        }

        // Print jarsigner*.properties entries as Resources*.java entries
        for (String fileName : RESOURCES_DIR.toFile().list()) {
            path = RESOURCES_DIR.resolve(fileName);
            System.out.println(System.lineSeparator() + "// " + path);
            Properties props = new Properties();
            InputStream is = Files.newInputStream(path);
            try (InputStreamReader isr = new InputStreamReader(is, "UTF-8")) {
                props.load(isr);
            }
            for (String propName : propNames) {
                String propVal = escape(props.getProperty(propName));
                System.out.println("        {\"" + propName + "\",");
                System.out.println("                \"" + propVal + "\"},");
            }
        }
    }
}
