/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 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.postinstall.task;

import com.google.auto.service.AutoService;
import org.apache.commons.lang3.SystemUtils;
import org.jboss.installer.core.InstallationData;
import org.jboss.installer.postinstall.PostInstallTask;
import org.jboss.installer.postinstall.SimplePostInstallTask;
import org.jboss.installer.postinstall.TaskPrinter;

import java.io.IOException;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;

@AutoService(PostInstallTask.class)
public class AddAdminUserTask implements SimplePostInstallTask {

    private static final String TASK_NAME = "post_install.task.add_user.name";

    @Override
    public String getName() {
        return TASK_NAME;
    }

    @Override
    public String getSerializationName() {
        return "add-admin";
    }

    @Override
    public boolean applyToInstallation(InstallationData data, TaskPrinter printer) {
        final Path installationDir = data.getTargetFolder();
        final String adminUsername = data.getAdminUsername();
        final String password = data.getPassword();

        printer.print("tasks.add_admin.started", adminUsername);

        // TODO: handle Windows as well
        final String scriptName;
        if (SystemUtils.IS_OS_WINDOWS) {
            scriptName = "add-user.bat";
        } else {
            scriptName = "add-user.sh";
        }
        final ProcessBuilder builder = new ProcessBuilder(installationDir.resolve("bin").resolve(scriptName).toString(), "-s",
                "-u", adminUsername, "-p", password);
        // TODO: capture the output
        builder.environment().put("NOPAUSE", "true");
        builder.environment().put("JAVA_HOME", System.getProperty("java.home"));
        try {
            final Process process = builder.start();
            if (process.waitFor(30, TimeUnit.SECONDS)) {
                if (process.exitValue() == 0) {
                    printer.print("tasks.add_admin.finished", adminUsername);
                    return true;
                } else {
                    printer.print("tasks.add_admin.failed", adminUsername);
                    return false;
                }
            } else {
                throw new RuntimeException("Process timed out during execution");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
}
