package com.firefrostgaming.bitchbot;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 * Renames our own jar to .jar.disabled after a successful first-boot run.
 *
 * On NeoForge 1.21.1 the mod jar is loaded via a custom classloader, but the
 * underlying file is still on disk in mods/. We locate it via this class's
 * ProtectionDomain → CodeSource → Location.
 *
 * The actual rename happens in-place. NeoForge keeps the file open for the
 * lifetime of the JVM, so on Windows the rename only sticks at next shutdown.
 * On Linux (which is what every Firefrost server is) the rename succeeds
 * immediately and the open file handle keeps working until restart. Either
 * way, on the NEXT boot the modloader skips .jar.disabled files.
 */
public class SelfDestruct {

    public static void disableOurJar() throws Exception {
        ProtectionDomain pd = SelfDestruct.class.getProtectionDomain();
        CodeSource cs = pd != null ? pd.getCodeSource() : null;
        if (cs == null || cs.getLocation() == null) {
            BitchBot.LOGGER.warn("[BitchBot] No CodeSource — cannot self-destruct.");
            return;
        }

        Path jarPath = Paths.get(cs.getLocation().toURI());
        if (!jarPath.toString().endsWith(".jar")) {
            BitchBot.LOGGER.warn("[BitchBot] CodeSource is not a .jar ({}) — cannot self-destruct.", jarPath);
            return;
        }

        Path target = jarPath.resolveSibling(jarPath.getFileName().toString() + ".disabled");
        try {
            Files.move(jarPath, target);
            BitchBot.LOGGER.info("[BitchBot] 💥 Self-destruct successful. {} → {}", jarPath.getFileName(), target.getFileName());
        } catch (java.nio.file.FileSystemException fse) {
            // Windows: file in use → schedule on JVM exit
            jarPath.toFile().deleteOnExit();
            BitchBot.LOGGER.warn("[BitchBot] Jar locked by JVM — scheduled deletion on shutdown ({}). Linux will rename immediately.", fse.getMessage());
        }
    }
}
