/*
 * 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.impl.secdom;

import org.jboss.dmr.ModelNode;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.postinstall.ldap.SecurityDomain;
import org.jboss.installer.postinstall.ldap.SecurityDomainModel;
import org.jboss.installer.postinstall.server.EmbeddedServer;
import org.jboss.installer.postinstall.task.secdom.PropertiesFileConfig;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import static org.jboss.installer.postinstall.task.SecurityDomainConfig.REALM_SUFFIX;
import static org.jboss.installer.postinstall.task.utils.ModelUtils.createEmptyOperation;
import static org.jboss.installer.postinstall.task.utils.ModelUtils.pathAddress;

public class PropertiesSecurity {

    private final TaskPrinter printer;

    public PropertiesSecurity(TaskPrinter printer) {
        this.printer = printer;
    }

    public List<ModelNode> toOperations(EmbeddedServer server, String domainName, PropertiesFileConfig propertiesFileConfig) throws IOException {
        final ArrayList<ModelNode> ops = new ArrayList<>();

        final boolean plainText = propertiesFileConfig.isPlainText();
        final String hashEncoding = propertiesFileConfig.getHashEncoding();
        final String hashCharset = propertiesFileConfig.getHashCharset();

        initPropertyFiles(domainName, propertiesFileConfig.getGroupsFilePath(), propertiesFileConfig.getUsersFilePath(), plainText);
        // add realm
        final ModelNode addRealmOp = addPropertyFileRealmOp(server, domainName, propertiesFileConfig.getGroupsFilePath(),
                propertiesFileConfig.getUsersFilePath(), plainText, hashEncoding, hashCharset);

        ops.add(addRealmOp);

        // add domain with the new realm
        final ModelNode addDomainOp = new SecurityDomain().createSecurityDomain(new SecurityDomainModel(domainName, domainName + REALM_SUFFIX, true));

        ops.add(addDomainOp);

        // In the future, we should add http-authentication-factory and application-security-domain
        return ops;
    }

    private ModelNode addPropertyFileRealmOp(EmbeddedServer server, String domainName, Path groupFileName, Path usersFileName, boolean plainText, String hashEncoding, String hashCharset) {
        final ModelNode addRealmOp = createEmptyOperation("add", pathAddress("subsystem", "elytron")
                .add("properties-realm", domainName + REALM_SUFFIX));
        addRealmOp.get("groups-attribute").set("group");
        final ModelNode groupsNode = server.relativise(groupFileName, new ModelNode());
        addRealmOp.get("groups-properties").set(groupsNode);

        final ModelNode usersNode = server.relativise(usersFileName, new ModelNode());
        usersNode.get("plain-text").set(plainText);
        addRealmOp.get("users-properties").set(usersNode);

        if (!plainText) {
            addRealmOp.get("hash-encoding").set(hashEncoding);
            addRealmOp.get("hash-charset").set(hashCharset);
        }

        return addRealmOp;
    }

    private void initPropertyFiles(String domainName, Path groupsFilePath, Path usersFilePath, boolean plainText) throws IOException {
        if (!Files.exists(usersFilePath)) {
            createFile(usersFilePath);
            if (!plainText) {
                // TODO: should add that as well if already existing, otherwise it won't work
                writeFile(domainName, usersFilePath);
            }
        }
        if (!Files.exists(groupsFilePath)) {
            createFile(groupsFilePath);
        }
    }

    private void writeFile(String domainName, Path filePath) throws IOException {
        try {
            Files.write(filePath, ("#$REALM_NAME=" + domainName + "-realm$").getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE);
        } catch (IOException e) {
            printer.print("tasks.sec_dom.file_write_error", filePath.toString());
            throw e;
        }
    }

    private Path createFile(Path filePath) throws IOException {
        try {
            return Files.createFile(filePath);
        } catch (IOException e) {
            printer.print("tasks.sec_dom.file_create_error", filePath.toString());
            throw e;
        }
    }

}
