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
import kotlin.system.exitProcess

class InstallTunnelServiceCmd : Command {
    override fun execute(args: Array<String>) {
        println("Executing InstallTunnelServiceCmd")
        val path = Utils.APP_DIR.toString() + "/configurations/" + args[1] + ".conf"
        println(WireGuardJNI().installTunnel(args[1], path))
        exitProcess(0)
    }

    override fun getName(): String {
        return "/installtunnelservice"
    }

    override fun getUsage(): String {
        return "(/path/to/tunnel/config)"
    }

    override fun getDescription(): String {
        return "Creates and starts a WireGuard Tunnel Service"
    }

    private var reservedNames: Array<String> = arrayOf(
        "CON", "PRN", "AUX", "NUL",
        "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
        "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
    )


    private fun isReserved(name: String): Boolean {
        if (name.isEmpty()) {
            return false
        }
        for (s in reservedNames) {
            if (name.contains(s)) {
                return true
            }
        }
        return false
    }

    private val specialChars = arrayOf("$", "\\", "/", ":", "*", "?", "\"", "'", "<", ">", "|", "\t", "\u0000")
    private fun hasSpecialChars(name: String): Boolean {
        for (s in specialChars) {
            if (name.contains(s)) {
                return true
            }
        }
        return false
    }

    private val pattern: Pattern = Pattern.compile("^[a-zA-Z0-9_=+.-]{1,32}$")
    private fun tunnelNameIsValid(name: String): Boolean {
        if (isReserved(name) || hasSpecialChars(name)) {
            return false
        }
        return pattern.matcher(name).hasMatch()
    }
}