<commit_before>package org.ovirt.engine.core.vdsbroker.vdsbroker;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.action.SysPrepParams;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigUtil;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.compat.TimeZoneInfo;
import org.ovirt.engine.core.dal.dbbroker.generic.DomainsPasswordMap;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;

public final class SysprepHandler {
    private static final Map<String, String> userPerDomain = new HashMap<String, String>();
    private static Map<String, String> passwordPerDomain = new HashMap<String, String>();
    public static final Map<String, Integer> timeZoneIndex = new HashMap<String, Integer>();

    // we get a string like "(GMT-04:30) Afghanistan Standard Time"
    // we use regex to extract the time only and replace it to number
    // in this sample we get -430
    public static String TimzeZoneExtractTimePattern = ".*(GMT[+,-]\\d{2}:\\d{2}).*";

    private static Log log = LogFactory.getLog(SysprepHandler.class);

    static {
        initTimeZones();
        fillUsersMap();
        fillPasswordsMap();
    }

    /**
     * TODO: This code is the exact code as in UsersDomainCacheManagerService, until we have a suitable location that
     * them both can use. Note that every change in one will probably require the same change in the other
     */
    private static void fillUsersMap() {
        String userPerDomainEntry = Config.<String> GetValue(ConfigValues.AdUserName);
        if (!userPerDomainEntry.isEmpty()) {
            String[] domainUserPairs = userPerDomainEntry.split(",");

            for (String domainUserPair : domainUserPairs) {
                String[] parts = domainUserPair.split(":");
                String domain = parts[0].trim().toLowerCase();
                String userName = parts[1].trim();

                userPerDomain.put(domain, userName);
            }
        }
    }

    /**
     * TODO: This code is the exact code as in UsersDomainCacheManagerService, until we have a suitable location that
     * them both can use. Note that every change in one will probably require the same change in the other
     */
    private static void fillPasswordsMap() {
        passwordPerDomain = Config.<DomainsPasswordMap> GetValue(ConfigValues.AdUserPassword);
    }

    public static String GetSysPrep(VM vm, String hostName, String domain, SysPrepParams sysPrepParams) {
        StringBuilder sysPrepContent = new StringBuilder();
        switch (vm.getStaticData().getos()) {
        case WindowsXP:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepXPPath)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey));
            break;

        case Windows2003:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K3Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2003));
            break;

        case Windows2003x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K3Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2003x64));
            break;

        case Windows2008:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008));
            break;

        case Windows2008x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8x64Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008x64));
            break;
        case Windows2008R2x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8R2Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008R2));
            break;

        case Windows7:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepWindows7Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKeyWindow7));
            break;

        case Windows7x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepWindows7x64Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKeyWindow7x64));
            break;

        default:
            break;
        }

        if (sysPrepContent.length() > 0) {

            populateSysPrepDomainProperties(sysPrepContent, domain, sysPrepParams);
            sysPrepContent = replace(sysPrepContent, "$ComputerName$", hostName != null ? hostName : "");
            sysPrepContent = replace(sysPrepContent, "$AdminPassword$", Config.<String> GetValue(ConfigValues.LocalAdminPassword));

            String timeZone = getTimeZone(vm);

            sysPrepContent = replace(sysPrepContent, "$TimeZone$", timeZone);
            sysPrepContent = replace(sysPrepContent, "$OrgName$", Config.<String> GetValue(ConfigValues.OrganizationName));
        }

        return sysPrepContent.toString();
    }

    private static void populateSysPrepDomainProperties(StringBuilder sysPrepContent,
            String domain,
            SysPrepParams sysPrepParams) {

        String domainName;
        String adminUserName;
        String adminPassword;

        if (sysPrepParams == null || StringUtils.isEmpty(sysPrepParams.getSysPrepDomainName())) {
            domainName = useDefaultIfNull("domain", domain, "", true);
        } else {
            domainName = sysPrepParams.getSysPrepDomainName();
        }

        if (sysPrepParams == null || sysPrepParams.getSysPrepUserName() == null
                || sysPrepParams.getSysPrepPassword() == null) {
            adminUserName = useDefaultIfNull("user", userPerDomain.get(domainName.toLowerCase()),
                    Config.<String> GetValue(ConfigValues.SysPrepDefaultUser), true);

            adminPassword = useDefaultIfNull("password", passwordPerDomain.get(domainName.toLowerCase()),
                    Config.<String> GetValue(ConfigValues.SysPrepDefaultPassword), false);
        } else {
            adminUserName = sysPrepParams.getSysPrepUserName();
            adminPassword = sysPrepParams.getSysPrepPassword();
        }

        // Get values from SysPrepParams - alternative for username,password and domain.
        sysPrepContent = replace(sysPrepContent, "$JoinDomain$", domainName);
        sysPrepContent = replace(sysPrepContent, "$DomainAdmin$", adminUserName);
        sysPrepContent = replace(sysPrepContent, "$DomainAdminPassword$", adminPassword);
    }

    static StringBuilder replace(StringBuilder sysPrepContent, String pattern, String value) {
        return new StringBuilder(sysPrepContent.toString().replaceAll(Pattern.quote(pattern), Matcher.quoteReplacement(value)));
    }

    private static String useDefaultIfNull(String key, String value, String defaultValue,
            boolean printDefaultValue) {
        if (value == null && printDefaultValue) {
            log.errorFormat("Could not find value for {0}. Going to use default value of: {1}",
                    key, defaultValue);
        }
        return value != null ? value : defaultValue;
    }

    private static String getTimeZone(VM vm) {
        String timeZone;
        // Can be empty if the VM was imported.
        if (StringUtils.isEmpty(vm.gettime_zone())) {<commit_msg>core: add marks for key-value in sysprep handler log (#870100)<commit_after>package org.ovirt.engine.core.vdsbroker.vdsbroker;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.action.SysPrepParams;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigUtil;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.compat.TimeZoneInfo;
import org.ovirt.engine.core.dal.dbbroker.generic.DomainsPasswordMap;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;

public final class SysprepHandler {
    private static final Map<String, String> userPerDomain = new HashMap<String, String>();
    private static Map<String, String> passwordPerDomain = new HashMap<String, String>();
    public static final Map<String, Integer> timeZoneIndex = new HashMap<String, Integer>();

    // we get a string like "(GMT-04:30) Afghanistan Standard Time"
    // we use regex to extract the time only and replace it to number
    // in this sample we get -430
    public static String TimzeZoneExtractTimePattern = ".*(GMT[+,-]\\d{2}:\\d{2}).*";

    private static Log log = LogFactory.getLog(SysprepHandler.class);

    static {
        initTimeZones();
        fillUsersMap();
        fillPasswordsMap();
    }

    /**
     * TODO: This code is the exact code as in UsersDomainCacheManagerService, until we have a suitable location that
     * them both can use. Note that every change in one will probably require the same change in the other
     */
    private static void fillUsersMap() {
        String userPerDomainEntry = Config.<String> GetValue(ConfigValues.AdUserName);
        if (!userPerDomainEntry.isEmpty()) {
            String[] domainUserPairs = userPerDomainEntry.split(",");

            for (String domainUserPair : domainUserPairs) {
                String[] parts = domainUserPair.split(":");
                String domain = parts[0].trim().toLowerCase();
                String userName = parts[1].trim();

                userPerDomain.put(domain, userName);
            }
        }
    }

    /**
     * TODO: This code is the exact code as in UsersDomainCacheManagerService, until we have a suitable location that
     * them both can use. Note that every change in one will probably require the same change in the other
     */
    private static void fillPasswordsMap() {
        passwordPerDomain = Config.<DomainsPasswordMap> GetValue(ConfigValues.AdUserPassword);
    }

    public static String GetSysPrep(VM vm, String hostName, String domain, SysPrepParams sysPrepParams) {
        StringBuilder sysPrepContent = new StringBuilder();
        switch (vm.getStaticData().getos()) {
        case WindowsXP:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepXPPath)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey));
            break;

        case Windows2003:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K3Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2003));
            break;

        case Windows2003x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K3Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2003x64));
            break;

        case Windows2008:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008));
            break;

        case Windows2008x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8x64Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008x64));
            break;
        case Windows2008R2x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8R2Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008R2));
            break;

        case Windows7:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepWindows7Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKeyWindow7));
            break;

        case Windows7x64:
            sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepWindows7x64Path)));
            sysPrepContent = replace(sysPrepContent, "$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKeyWindow7x64));
            break;

        default:
            break;
        }

        if (sysPrepContent.length() > 0) {

            populateSysPrepDomainProperties(sysPrepContent, domain, sysPrepParams);
            sysPrepContent = replace(sysPrepContent, "$ComputerName$", hostName != null ? hostName : "");
            sysPrepContent = replace(sysPrepContent, "$AdminPassword$", Config.<String> GetValue(ConfigValues.LocalAdminPassword));

            String timeZone = getTimeZone(vm);

            sysPrepContent = replace(sysPrepContent, "$TimeZone$", timeZone);
            sysPrepContent = replace(sysPrepContent, "$OrgName$", Config.<String> GetValue(ConfigValues.OrganizationName));
        }

        return sysPrepContent.toString();
    }

    private static void populateSysPrepDomainProperties(StringBuilder sysPrepContent,
            String domain,
            SysPrepParams sysPrepParams) {

        String domainName;
        String adminUserName;
        String adminPassword;

        if (sysPrepParams == null || StringUtils.isEmpty(sysPrepParams.getSysPrepDomainName())) {
            domainName = useDefaultIfNull("domain", domain, "", true);
        } else {
            domainName = sysPrepParams.getSysPrepDomainName();
        }

        if (sysPrepParams == null || sysPrepParams.getSysPrepUserName() == null
                || sysPrepParams.getSysPrepPassword() == null) {
            adminUserName = useDefaultIfNull("user", userPerDomain.get(domainName.toLowerCase()),
                    Config.<String> GetValue(ConfigValues.SysPrepDefaultUser), true);

            adminPassword = useDefaultIfNull("password", passwordPerDomain.get(domainName.toLowerCase()),
                    Config.<String> GetValue(ConfigValues.SysPrepDefaultPassword), false);
        } else {
            adminUserName = sysPrepParams.getSysPrepUserName();
            adminPassword = sysPrepParams.getSysPrepPassword();
        }

        // Get values from SysPrepParams - alternative for username,password and domain.
        sysPrepContent = replace(sysPrepContent, "$JoinDomain$", domainName);
        sysPrepContent = replace(sysPrepContent, "$DomainAdmin$", adminUserName);
        sysPrepContent = replace(sysPrepContent, "$DomainAdminPassword$", adminPassword);
    }

    static StringBuilder replace(StringBuilder sysPrepContent, String pattern, String value) {
        return new StringBuilder(sysPrepContent.toString().replaceAll(Pattern.quote(pattern), Matcher.quoteReplacement(value)));
    }

    private static String useDefaultIfNull(String key, String value, String defaultValue,
            boolean printDefaultValue) {
        if (value == null && printDefaultValue) {
            log.warnFormat("Could not find value for key '{0}'. Going to use default value of: '{1}'",
                    key, defaultValue);
        }
        return value != null ? value : defaultValue;
    }

    private static String getTimeZone(VM vm) {
        String timeZone;
        // Can be empty if the VM was imported.
        if (StringUtils.isEmpty(vm.gettime_zone())) {
{'fraction_non_alphanumeric': 0.10372308066674778, 'fraction_numerical': 0.011436914466480107, 'mean_word_length': 3.23031394750386, 'pattern_counts': {'":': 2, '<': 59, '<?xml version=': 0, '>': 61, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1095558', 'n_tokens_mistral': 4584, 'n_tokens_neox': 4256, 'n_words': 966}