package tech.nevets.tvpn.cli.commands;

import tech.nevets.tvpn.Utils;
import tech.nevets.tvpn.cli.Command;
import tech.nevets.tvpn.wg.WireGuardJNI;

import java.util.regex.Pattern;

public class InstallTunnelServiceCmd implements Command {
    @Override
    public void execute(String[] args) {


        System.out.println("Executing InstallTunnelServiceCmd");
        String path = Utils.APP_DIR + "/configurations/" + args[1] + ".conf";
        System.out.println(new WireGuardJNI().installTunnel(args[1], path));
        System.exit(0);
    }

    @Override
    public String getName() {
        return "/installtunnelservice";
    }

    @Override
    public String getUsage() {
        return "(/path/to/tunnel/config)";
    }

    @Override
    public String getDescription() {
        return "Creates and starts a WireGuard Tunnel Service";
    }

    String[] reservedNames = new String[]{
        "CON", "PRN", "AUX", "NUL",
                "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
                "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
    };


    private boolean isReserved(String name) {
        if (name.isEmpty()) {
            return false;
        }
        for (String s : reservedNames) {
            if (name.contains(s)) {
                return true;
            }
        }
        return false;
    }

    private static final String[] SPECIAL_CHARS = new String[]{"$", "\\", "/", ":", "*", "?", "\"", "'", "<", ">", "|", "\t", "\00"};
    private boolean hasSpecialChars(String name) {
        for (String s : SPECIAL_CHARS) {
            if (name.contains(s)) {
                return true;
            }
        }
        return false;
    }

    private static final Pattern PATTERN = Pattern.compile("^[a-zA-Z0-9_=+.-]{1,32}$");
    private boolean tunnelNameIsValid(String name) {
        if (isReserved(name) || hasSpecialChars(name)) {
            return false;
        }
        return PATTERN.matcher(name).hasMatch();
    }
}
