#!/bin/bash
#
# This helper script is part of produceReport.sh

function check_hosts_health() {
    # Hosts health validation
    sql_cmd=$(cat "${SQLS}"/hosts_query_check_health.sql)
    hosts_health_check=$(executeSQL "${sql_cmd}")
    if [ ${#hosts_health_check} -gt 0 ]; then
        echo -e "{WARNING} The following hosts are not ready for upgrade:"
        printTable "${sql_cmd}"
        echo
    else
        echo -e "{OK} No blocker status found in the hosts\n"
    fi
}

function check_hosts_pretty_name() {
    # Hosts pretty name value validation
    hosts_pretty_name=$(execute_SQL_from_file "${SQLS}"/hosts_query_check_pretty_name.sql)
    if [ ${#hosts_pretty_name} -gt 0 ]; then
        echo "{WARNING} List of hosts with empty OS description value which " \
             "may cause Host type not to be recognized correctly. Such hosts" \
             " will need to be reinstalled after upgrade to work properly."
        echo "${hosts_pretty_name}" | createAsciidocTable "noheader"
    else
        echo -e "{OK} No hosts with empty OS description\n"
    fi
}

function check_vms_health() {
    # Virtual Machines health validation
    vms_health_check=$(execute_SQL_from_file "${SQLS}"/vms_query_health.sql)
    if [ ${#vms_health_check} -gt 0 ]; then
        echo "{WARNING} The following VMs are not ready for upgrade:"
        echo "${vms_health_check}" | createAsciidocTable "noheader"
    else
        echo -e "{OK} No blocker status found in the VMs\n"
    fi
}

function check_cluster_no_dc() {
    # Clusters without datacenter validation
    cluster_no_dc=$(execute_SQL_from_file "${SQLS}"/cluster_query_check_datacenter.sql)
    if [ ${#cluster_no_dc} -gt 0 ]; then
        echo
        echo "{WARNING} The following cluster(s) have no datacenter assigned:"
	echo "${cluster_no_dc}" | createAsciidocTable "noheader"
        echo
    else
        echo -e "{OK} All clusters contain datacenter assigned\n"
    fi
}

function check_third_party_certificate() {
    # Third party certificate validation
    pki_file_path=$(find "${SOS_REPORT_UNPACK_DIR}" -name ${ENGINE_PKI_FILE})
    if [[ $? != 0 ]]; then
        echo "Could not find ${ENGINE_PKI_FILE} in the sosreport, exiting"
        exit $?
    fi
    dir_pki_conf=$(dirname "${pki_file_path}")

    # Read the variables from conf files in /etc/ovirt-engine/engine.conf.d
    for file in ${dir_pki_conf}/*.conf
    do
        [ -f "$file" ] && source $file
    done

    if [ ! -z "${ENGINE_PKI_TRUST_STORE}" ] && [ "${ENGINE_PKI_TRUST_STORE}" != ${DEFAULT_PKI_TRUSTSTORE} ]; then
        echo
        echo "- PKI Trust Store:"
        echo "{WARNING} ENGINE_PKI_TRUST_STORE has non-default value"
        echo "ENGINE_PKI_TRUST_STORE defaults to ${DEFAULT_PKI_TRUSTSTORE}"
        echo "ENGINE_PKI_TRUST_STORE is currently ${ENGINE_PKI_TRUST_STORE}"
        echo
        echo "To change this value, use the files in ${ENGINE_PKI_CONF_DIR}"
        echo
        echo "For more information about this topic, see also:"
        echo "https://bugzilla.redhat.com/1336838"
    else
        echo -e "{OK} ENGINE_PKI_TRUST_STORE has default value\n"
    fi
}

function check_min_and_max_engine_heap() {
    # Based on
    # https://github.com/oVirt/ovirt-engine/blob/1e7d0dd7e11b1db035660491e37fbf0368614bd6/packaging/services/ovirt-engine/ovirt-engine.py#L311-L338
    # https://github.com/oVirt/ovirt-engine/blob/1e7d0dd7e11b1db035660491e37fbf0368614bd6/packaging/pythonlib/ovirt_engine/mem.py#L29-L85
    ENGINE_CONF_D_10_SETUP_JAVA=$(find "${SOS_REPORT_UNPACK_DIR}" -name 10-setup-java.conf | grep engine.conf.d | head -n 1 2> /dev/null)
    if [ -z ${ENGINE_CONF_D_10_SETUP_JAVA} ]; then
        return
    fi

    . ${ENGINE_CONF_D_10_SETUP_JAVA}
    ENGINE_HEAP_MIN="${ENGINE_HEAP_MIN//[!0-9]/}"
    ENGINE_HEAP_MAX="${ENGINE_HEAP_MAX//[!0-9]/}"

    MEMINFO_ENGINE=$(find "${SOS_REPORT_UNPACK_DIR}" -name meminfo)
    TOTAL_MEM_MB=$(cat ${MEMINFO_ENGINE} | grep MemTotal | awk {'print int($2/1024)'})
    if [ -z ${TOTAL_MEM_MB} ]; then
        return
    fi

    ret=0
    if [ -z "${ENFORCE_ENGINE_HEAP_PARAMS}" ]; then
        if [ ! -z "${ENGINE_HEAP_MIN}" ] && [ ${ENGINE_HEAP_MIN} -gt ${TOTAL_MEM_MB} ]; then
            echo -e "{WARNING} ENGINE_HEAP_MIN ${ENGINE_HEAP_MIN} MB is higher than total memory available ${TOTAL_MEM_MB} MB\n"
            ret=-1
        fi
        if [ ! -z "${ENGINE_HEAP_MAX}" ] && [ ${ENGINE_HEAP_MAX} -gt ${TOTAL_MEM_MB} ]; then
            echo -e "{WARNING} ENGINE_HEAP_MAX ${ENGINE_HEAP_MAX} MB is higher than total memory available ${TOTAL_MEM_MB} MB\n"
            ret=-1
        fi
    fi

    if [ ${ret} = 0 ]; then
        echo -e "{OK} ENGINE_HEAP_MAX and ENGINE_HEAP_MIN are lower than total memory available\n"
    fi
}

function check_vms_running_obsolete_cluster() {
    # In oVirt Engine 4.0, the minimum cluster level supported is 3.6.
    # So we must inform in case there is vm in 3.5 cluster level
    vms_out_date=$(execute_SQL_from_file "${SQLS}"/vms_query_check_obsolete_cluster.sql)
    if [ ${vms_out_date} -gt 0 ]; then
        echo "{WARNING} There are ${vms_out_date} VMs in version 3.5 and prior clusters. These clusters need to be upgraded to version 3.6 prior upgrading to version 4.0."
        echo "See 3.6 Upgrade Considerations:"
        echo -e "https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Virtualization/3.6/html/Upgrade_Guide/Red_Hat_Enterprise_Virtualization_3.6_Upgrade_Considerations.html\n"
    else
        echo -e "{OK} All virtual machines have cluster level >= 3.6\n"
    fi
}

function check_vms_with_no_timezone_set() {
    sql_cmd=$(cat "${SQLS}"/vms_check_no_timezone_set.sql)
    vms_no_timezone_set=$(executeSQL "${sql_cmd}")
    if [ ${#vms_no_timezone_set} -gt 0 ]; then
        echo -e "{WARNING} The following virtual machine(s) have no timezone set and might affect cluster upgrade."
        echo "We recommend update it manually via Engine Web Admin, related bugzilla report:"
        echo "https://bugzilla.redhat.com/show_bug.cgi?id=1386507"
        printTable "${sql_cmd}"
        echo
    else
        echo -e "{OK} Timezone is set for all virtual machines\n"
    fi
}

function check_mixedrhelversion() {
    sql_cmd=$(cat "${SQLS}"/vdc_options_query_checkmixedrhelversion.sql)
    sql_ret=$(executeSQL "${sql_cmd}")
    if [ ${#sql_ret} -gt 0 ]; then
        echo -e "{WARNING} *After* upgrading all hosts to EL7 and *BEFORE* " \
                "upgrading the Manager to >= 4.y make sure " \
                "CheckMixedRhelVersions is true. More information about " \
                "this topic check: [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Virtualization/3.6/html/Upgrade_Guide/Upgrading_Hosts_in_a_Red_Hat_Enterprise_Linux_6_Cluster_to_Red_Hat_Enterprise_Linux_7.html]"
        printTable "${sql_cmd}"
        echo
    else
        echo -e "{OK} CheckMixedRhelVersions validation\n"
    fi
}

function rpm_version() {
    find "${SOS_REPORT_UNPACK_DIR}" -name "installed-rpms" -exec grep '(engine\|ovirt\|postgresql\|rhevm\|spice\| )' '{}' \; | cut -f 1 -d " " | sort
}

function check_vms_windows_with_incorrect_timezone() {
   sql_ret=$(execute_SQL_from_file "${SQLS}"/vms_query_windows_vms_with_incorrect_timezone.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo -e "{WARNING} The following VMs with Windows OS contain incorrect" \
                " timezone, please adjust the timezone via Web Admin. A list " \
                "of possible values can be found via: [https://github.com/oVirt/ovirt-engine/blob/master/backend/manager/modules/compat/src/main/java/org/ovirt/engine/core/compat/WindowsJavaTimezoneMapping.java]"
        echo "${sql_ret}" | createAsciidocTable "noheader"
    else
        echo -e "{OK} All VMs with Windows OS have correct timezone\n"
    fi
}

function check_vms_linux_and_others_with_incorrect_timezone() {
   sql_ret=$(execute_SQL_from_file "${SQLS}"/vms_query_linux_and_others_vms_with_incorrect_timezone.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo -e "{WARNING} The following VMs with Linux OS or marked as " \
                "Other OS contain incorrect timezone, please adjust the " \
                "timezone via Web Admin. A list of possible values can " \
                "be found via: [https://github.com/oVirt/ovirt-engine/blob/5ec729e5f8b5504b5c166c6d4217267a9bda7728/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/TimeZoneType.java#L20-L103]"
        echo "${sql_ret}" | createAsciidocTable "noheader"
    else
        echo -e "{OK} All VMs with Linux or Other OS have correct timezone\n"
    fi
}

function check_vms_with_cluster_lower_3_6_with_virtio_serial_console() {
   sql_ret=$(execute_SQL_from_file "${SQLS}"/vms_with_cluster_lower_3_6_with_virtio_serial_console.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo -e "{WARNING} The following VMs with VirtIO serial console " \
                "enabled in cluster levels 3.5 and below cannot be later " \
                "live migrated to 3.6 hosts (on RHEL7). Such attempt fails " \
                "and VM is terminated. You need to disable the VirtIO serial " \
                "console feature while the VM is still in a 3.5 cluster. " \
                "It can be re-enabled once the VM is in a 3.6 cluster." \
                "Related bug report: [https://bugzilla.redhat.com/show_bug.cgi?id=1434401]"
        echo "${sql_ret}" | createAsciidocTable "noheader"
    else
        echo -e "{OK} No VMs with VirtIO serial console enabled in cluster" \
                " levels 3.5 and below\n"
    fi
}

function check_async_tasks() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/async_tasks_query_running_tasks.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo
        echo "{WARNING} The following async tasks are still running. " \
             "Please make sure that there are no running tasks before any " \
             "engine upgrade. You might use taskcleaner.sh tool, see: " \
             "https://github.com/oVirt/ovirt-engine/blob/bf3abca7848496f7cf60d44d9335e2ec0bd3f852/packaging/setup/dbutils/taskcleaner.sh"
        echo "${sql_ret}" | createAsciidocTable "noheader"
        echo
    else
        echo -e "{OK} No async tasks running in Engine\n"
    fi
}

function check_runnning_commands() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/command_entities_query_get_running_commands.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo
        echo "{WARNING} The following commands are still running. " \
             "Please make sure that there are no commands running before any " \
             "engine upgrade. You might use taskcleaner.sh tool, see: " \
             "https://github.com/oVirt/ovirt-engine/blob/bf3abca7848496f7cf60d44d9335e2ec0bd3f852/packaging/setup/dbutils/taskcleaner.sh"
        echo "${sql_ret}" | createAsciidocTable "noheader"
        echo
    else
        echo -e "{OK} No commands running in Engine\n"
    fi
}

function check_compensation_tasks() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/business_entity_snapshot_query_running_compensation_tasks.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo
        echo "{WARNING} The following compensation tasks are still running. " \
             "Please make sure that there are no running tasks before any " \
             "engine upgrade. You might use taskcleaner.sh tool, see: " \
             "https://github.com/oVirt/ovirt-engine/blob/bf3abca7848496f7cf60d44d9335e2ec0bd3f852/packaging/setup/dbutils/taskcleaner.sh"
        echo "${sql_ret}" | createAsciidocTable "noheader"
        echo
    else
        echo -e "{OK} No compensation tasks running in Engine\n"
    fi
}

function check_storage_domains_failing() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/storage_domains_query_get_failing_domains.sql)
    if [ ${#sql_ret} -gt 0 ]; then
        echo
        echo "{WARNING} The following storage domains are inactive. " \
             "Please make sure all storage domains required for the system " \
             "are available and active before upgrading the environment"
        echo "${sql_ret}" | createAsciidocTable "noheader"
        echo
    else
        echo -e "{OK} No storage domain inactive\n"
    fi
}

function check_AAA_legacy() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/vdc_options_query_AAA_legacy.sql)
    if [ $(echo "${sql_ret}" | wc -l) -gt 1 ]; then
        echo
        echo "{WARNING} Legacy LDAP provider detected, **before upgrade** the environment use: " \
             "https://github.com/oVirt/ovirt-engine-kerbldap-migration/[ovirt-engine-kerbldap-migration tool]" \
             "to ease migrate into the new ovirt-engine-extension-aaa-ldap provider"
        echo "${sql_ret}" | createAsciidocTable
        echo
    else
        echo -e "{OK} No Legacy LDAP provider detected\n"
    fi
}

function check_minimum_cluster_compat_version() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/cluster_query_minimum_3_6_compat_version.sql)
    if [ $(echo "${sql_ret}" | wc -l) -gt 1 ]; then
        echo
        echo "{WARNING} It's required to update the **Cluster Compatibility Version to 3.6" \
             " before** upgrading to 4.0 for the following cluster(s):"
        echo "${sql_ret}" | createAsciidocTable
        echo
    else
        echo -e "{OK} Cluster(s) are 3.6 or higher in Compatibility Version\n"
    fi
}

function check_minimum_datacenter_compat_version() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/datacenter_query_minimum_3_6_compat_version.sql)
    if [ $(echo "${sql_ret}" | wc -l) -gt 1 ]; then
        echo
        echo "{WARNING} It's required to update the **DataCenter Compatibility Version to 3.6" \
             " before** upgrading to 4.0 for the following DataCenter(s):"
        echo "${sql_ret}" | createAsciidocTable
        echo
    else
        echo -e "{OK} DataCenter(s) are 3.6 or higher in Compatibility Version\n"
    fi
}

function check_non_ovirtmgmt_as_management_network() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/network_query_cluster_with_non_ovirtmgmt_as_management_network.sql)
    if [ $(echo "${sql_ret}" | wc -l) -gt 1 ]; then
        echo
        echo "{WARNING} There are cluster(s) with **NON ovirtmgmt as management network**." \
             "Hosted Engine environments can be affected during upgrade. See " \
             "https://bugzilla.redhat.com/show_bug.cgi?id=1449547[bz#1449547] and " \
             "https://access.redhat.com/solutions/2292861[this knowledge article] for more information."
        echo "${sql_ret}" | createAsciidocTable
        echo
    else
        echo -e "{OK} All management network are ovirtmgmt\n"
    fi
}

function check_pinned_virtual_machines() {
    sql_ret=$(execute_SQL_from_file "${SQLS}"/vms_query_pinned_virtual_machines.sql)
    if [ $(echo "${sql_ret}" | wc -l) -gt 1 ]; then
        echo
        echo "{WARNING} There are virtual machine(s) pinned, it's not recommended upgrade" \
             " the environment with virtual machines pinned to run in specific hypervisors"
        echo "${sql_ret}" | createAsciidocTable
        echo
    else
        echo -e "{OK} No virtual machines pinned to specific hypervisor\n"
    fi
}
