/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2023 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.installer.cleaner;

import java.io.File;
import java.nio.file.Path;

/**
 * Cleans up leftover files that cannot be removed by main process (eg. due to resource locking).
 *
 * The {@code main} method should be called in a new process, started right before the parent process exits.
 * The process should be called with classpath of extracted classes (rather than JAR). This allows to clean up the classpath.
 *
 * <b>NOTE:</b> any classes and resources (outside JVM) used by this class, need to be extracted by {@link CleanerBuilder} into temporary folder.
 */
public class Cleaner {

    /**
     * entry point for cleaner process. Takes a number of {@code deletePath} argument recursively removing the paths.
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // short delay to make sure parent process finished and released locks
        Thread.sleep(500);

        for (String arg : args) {
            final String[] splitArg = arg.split("=");
            final String name = splitArg[0];
            final File targetFile = Path.of(splitArg[1]).toFile();
            if (name.equals("-DdeletePath") && targetFile.exists()) {
                deleteAll(targetFile);
            }
        }
    }

    private static void deleteAll(File file) {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                deleteAll(child);
            }
        }
        file.delete();
    }
}
