package de.ids_mannheim.korapxmltools

import java.io.IOException
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermissions

class ChangeZipPermissions {

    @Throws(IOException::class)
    fun changePermissions(zipFilePath: String?, permissions: String?) {
        val env: MutableMap<String, String?> = HashMap()
        env["create"] = "true"

        val zipFile = zipFilePath?.let { Paths.get(it) }
        val perms = PosixFilePermissions.fromString(permissions)
        FileSystems.newFileSystem(zipFile, env).use { fs ->
            val root = fs.getPath("/")
            Files.walk(root)
                .filter { path: Path? ->
                    Files.isRegularFile(
                        path
                    )
                }
                .forEach { file: Path ->
                    try {
                        // BasicFileAttributeView bv = Files.getFileAttributeView(file, BasicFileAttributeView.class);
                        // System.out.println("Setting permissions for file: " + file.toString()+ " from " + bv.readAttributes().toString() + " to " + permissions);
                        Files.setAttribute(file, "permissions", perms)
                    } catch (e: IOException) {
                        System.err.println("Failed to set permissions for file: $file")
                    }
                }
        }
    }
}

fun main(args: Array<String>) {
    if (args.size != 2) {
        println("Usage: java -jar changezippermissions <zipFilePath> <permissions>")
        println("Example: java -jar changezippermissions files.zip rw-rw-rw-")
        return
    }

    val zipFilePath = args[0]
    val permissions = args[1]

    try {
        ChangeZipPermissions().changePermissions(zipFilePath, permissions)
        println("Permissions changed successfully.")
    } catch (e: IOException) {
        System.err.println("Error: " + e.message)
    }
}

