package org.bdware.sc;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bdware.sc.util.FileUtil;
import org.zz.gmhelper.SM2KeyPair;
import org.zz.gmhelper.SM2Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class SM2Helper {
    public static void main(String[] args) {

        SM2KeyPair pair = SM2Util.generateSM2KeyPair(new SecureRandom());
        try {
            if (args.length > 0 && args[0].equals("generateKeyToFile")) {
                backupFile(new File("./manager.keypair"));
                backupFile(new File("./manager.key"));
                System.out.println("Generate file: manger.key, manager.keypair");
                FileOutputStream fout = new FileOutputStream("./manager.keypair");
                fout.write(pair.toJson().getBytes(StandardCharsets.UTF_8));
                fout.close();
                fout = new FileOutputStream("./manager.key");
                fout.write(pair.getPublicKeyStr().getBytes(StandardCharsets.UTF_8));
                fout.close();
            } else if (args.length > 0 && args[0].equals("generateCMConfig")) {
                backupFile(new File("./cmconfig.json"));
                System.out.println("Generate file: cmconfig.json");
                String content = FileUtil.getFileContent("./cmconfig.json.template");
                JsonObject jo = JsonParser.parseReader(new FileReader("cmvar.json")).getAsJsonObject();
                for (String key : jo.keySet()) {
                    content = content.replaceAll(key, jo.get(key).getAsString());
                }
                JsonObject keypair = JsonParser.parseReader(new FileReader("manager.keypair")).getAsJsonObject();
                content = content.replaceAll("_PRIVKEY", keypair.get("privateKey").getAsString());
                content = content.replaceAll("_PUBKEY", keypair.get("publicKey").getAsString());
                content = content.replaceAll("CMI", System.currentTimeMillis() + "");
                FileOutputStream fout = new FileOutputStream("./cmconfig.json");
                fout.write(content.getBytes(StandardCharsets.UTF_8));
                fout.close();
            } else
                System.out.println(pair.toJson());
            printHelp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printHelp() {
        String usage = "Usage:\n";
        usage += "java -cp cp/libs/*:cp/yjs.jar org.bdware.sc.SM2Helper generateCMConfig\n";
        usage += "java -cp cp/libs/*:cp/yjs.jar org.bdware.sc.SM2Helper generateKeyToFile";
        System.out.println(usage);
    }

    private static void backupFile(File file) {
        if (!file.exists()) return;
        File backup = null;
        for (int i = 0; i <= 100; i++) {
            if (i == 100) throw new IllegalArgumentException("failed to backup:" + file.getAbsolutePath());
            backup = new File(file.getParent(), file.getName() + "." + i);
            if (!backup.exists())
                break;
        }
        FileUtil.copyFile(file, backup);
        System.out.println("Backup: " + file.getAbsolutePath() + " --> " + backup.getAbsolutePath());
    }
}
