#!/usr/bin/python3
#
# Copyright (c) 2023--2025 SUSE LLC
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# SPDX-License-Identifier: GPL-2.0-only
#
#  pylint: disable=missing-module-docstring,invalid-name

import filecmp
import re
import sys
import os
import os.path
import uuid
import shutil
import subprocess
from pathlib import Path
from spacewalk.common.rhnConfig import cfg_component
from spacewalk.server import rhnSQL
from spacewalk.server.rhnUser import encrypt_password


def check_and_configure_fips():
    fips_enabled = False
    fips_path = Path("/proc/sys/crypto/fips_enabled")
    try:
        fips_enabled = fips_path.read_text(encoding="utf-8").strip() == "1"
    except FileNotFoundError:
        return
    except OSError as error:
        sys.stderr.write(f"Failed to read FIPS status: {error}\n")
        sys.stderr.flush()
        return

    if fips_enabled:
        result = subprocess.run(
            ["/usr/bin/update-crypto-policies", "--set", "FIPS"],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            encoding="utf-8",
            check=False,
        )
        if result.stdout:
            sys.stdout.write(f"{result.stdout}\n")
            sys.stdout.flush()
        if result.returncode:
            sys.stdout.write("Failed to set crypto policy to FIPS!\n")
            sys.stdout.flush()


def run_uyuni_configfiles_sync():
    if not os.path.isfile("/usr/bin/uyuni-configfiles-sync"):
        return 0

    exitCode = 0
    result = subprocess.run(
        ["/usr/bin/uyuni-configfiles-sync", "sync"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        encoding="utf-8",
        check=False,
    )

    if result.stdout:
        sys.stdout.write(f"{result.stdout}\n")
        sys.stdout.flush()
    if result.returncode:
        sys.stdout.write(
            "Failed to synchronize files to persistent volumes. Aborting!\n"
        )
        sys.stdout.flush()
        exitCode = 1
    return exitCode


# rhn.conf keys which moved into the rhnConfiguration table
DB_CONFIG_KEYS = {
    "server.max_passwd_len": "PSW_CHECK_LENGTH_MAX",
    "max_passwd_len": "PSW_CHECK_LENGTH_MAX",
    "server.min_passwd_len": "PSW_CHECK_LENGTH_MIN",
    "min_passwd_len": "PSW_CHECK_LENGTH_MIN",
    "server.satellite.http_proxy": "HTTP_PROXY",
    "server.satellite.http_proxy_username": "HTTP_PROXY_USERNAME",
    "server.satellite.http_proxy_password": "HTTP_PROXY_PASSWORD",
    "server.satellite.no_proxy": "NO_PROXY",
    "server.min_user_len": "USER_LOGIN_LENGTH_MIN",
    "web.min_user_len": "USER_LOGIN_LENGTH_MIN",
    "min_user_len": "USER_LOGIN_LENGTH_MIN",
    "server.max_user_len": "USER_LOGIN_LENGTH_MAX",
    "web.max_user_len": "USER_LOGIN_LENGTH_MAX",
    "max_user_len": "USER_LOGIN_LENGTH_MAX",
    "server.max_email_len": "USER_EMAIL_LENGTH_MAX",
    "web.max_email_len": "USER_EMAIL_LENGTH_MAX",
    "max_email_len": "USER_EMAIL_LENGTH_MAX",
    "server.satellite.reposync_download_threads": "REPOSYNC_DOWNLOAD_THREADS",
    "server.reposync_download_threads": "REPOSYNC_DOWNLOAD_THREADS",
    "reposync_download_threads": "REPOSYNC_DOWNLOAD_THREADS",
    "server.satellite.reposync_timeout": "REPOSYNC_TIMEOUT",
    "server.reposync_timeout": "REPOSYNC_TIMEOUT",
    "reposync_timeout": "REPOSYNC_TIMEOUT",
    "server.satellite.reposync_minrate": "REPOSYNC_MINRATE",
    "server.reposync_minrate": "REPOSYNC_MINRATE",
    "reposync_minrate": "REPOSYNC_MINRATE",
    "server.satellite.reposync_nevra_filter": "REPOSYNC_NEVRA_FILTER",
    "server.reposync_nevra_filter": "REPOSYNC_NEVRA_FILTER",
    "reposync_nevra_filter": "REPOSYNC_NEVRA_FILTER",
    "server.susemanager.sync_source_packages": "SYNC_SOURCE_PACKAGES",
    "server.sync_source_packages": "SYNC_SOURCE_PACKAGES",
    "sync_source_packages": "SYNC_SOURCE_PACKAGES",
    "server.satellite.urlgrabber_logspec": "URLGRABBER_LOGSPEC",
    "server.urlgrabber_logspec": "URLGRABBER_LOGSPEC",
    "urlgrabber_logspec": "URLGRABBER_LOGSPEC",
}


def move_config_to_db():
    """
    Move configuration values from /etc/rhn/rhn.conf into the rhnConfiguration table
    """
    rhnSQL.initDB()

    with open("/etc/rhn/rhn.conf", "r", encoding="utf8") as f:
        lines = f.readlines()

    remaining = []
    for line in lines:
        match = re.match(r"^\s*([\w.]+)\s*=(.*)$", line)
        key = DB_CONFIG_KEYS.get(match.group(1).lower()) if match else None
        if not key or not move_configuration(key, match.group(2).strip()):
            remaining.append(line)

    if len(remaining) == len(lines):
        return
    rhnSQL.commit()
    with open("/etc/rhn/rhn.conf", "w", encoding="utf8") as f:
        f.writelines(remaining)


# rhn.conf keys which got a new name
RENAMED_CONFIG_KEYS = {
    # moved from rhn_server_satellite.conf to rhn_server.conf
    "server.satellite.mount_point": "server.mount_point",
    "server.satellite.sync_cache_dir": "server.sync_cache_dir",
    # global keys used by all components
    "web.default_mail_from": "default_mail_from",
}


def rename_config_keys():
    """
    Rename keys in /etc/rhn/rhn.conf which got a new name
    """
    with open("/etc/rhn/rhn.conf", "r", encoding="utf8") as f:
        lines = f.readlines()

    renamed = []
    for line in lines:
        match = re.match(r"^(\s*)([\w.]+)(\s*=.*)$", line, re.DOTALL)
        new_key = RENAMED_CONFIG_KEYS.get(match.group(2).lower()) if match else None
        if new_key:
            line = match.group(1) + new_key + match.group(3)
        renamed.append(line)

    if renamed == lines:
        return
    with open("/etc/rhn/rhn.conf", "w", encoding="utf8") as f:
        f.writelines(renamed)


def move_configuration(key, value):
    """
    Store the value in the database. A value matching the default value is stored as NULL.
    """
    h = rhnSQL.prepare("""
            UPDATE rhnConfiguration
               SET value = CASE WHEN COALESCE(default_value, '') = :val THEN NULL ELSE :val END
             WHERE key = :key
            """)
    rowcount = h.execute(val=value, key=key)
    if rowcount != 1:
        # update failed
        sys.stdout.write(f"Failed to move {key} into DB\n")
        sys.stdout.flush()
        return False
    return True


def hash_plain_text_passwords():
    """
    Hash user passwords which are still stored in plain text.
    Values in a known hash format (PBKDF2-SHA256, SHA-256 crypt and the MD5 crypt
    random passwords of PAM users) are kept.
    """
    rhnSQL.initDB()
    h = rhnSQL.prepare("""
            SELECT id, password
              FROM web_contact
             WHERE password NOT LIKE '$pbkdf2-sha256$%'
               AND password NOT LIKE '$5$%'
               AND password NOT LIKE '$1$%'
               AND password <> ''
            """)
    h.execute()
    rows = h.fetchall_dict() or []
    if not rows:
        return

    update = rhnSQL.prepare("""
            UPDATE web_contact
               SET password = :password
             WHERE id = :id
            """)
    for row in rows:
        update.execute(password=encrypt_password(row["password"]), id=row["id"])
    rhnSQL.commit()
    sys.stdout.write(f"Hashed {len(rows)} plain text user passwords\n")
    sys.stdout.flush()


def init_scc_login():
    # pylint: disable-next=invalid-name
    with cfg_component("server.susemanager") as CFG:
        try:
            if CFG.scc_backup_srv_usr:
                # nothing to do
                return
        except AttributeError:
            # key does not exist, we need to create it
            pass

    scc_cred_file = "/etc/zypp/credentials.d/SCCcredentials"

    uuid_num = None
    if os.path.exists(scc_cred_file):
        with open(scc_cred_file, "r", encoding="utf8") as f:
            for line in f:
                if line.startswith("username"):
                    _, v = line.split("=", 2)
                    uuid_num = v.strip()
                    break
    if not uuid_num:
        # scc expects either a SCC machine login (must exists in SCC)
        # or a UUID4 following rfc4122 to identify a anonyme proxy
        uuid_num = str(uuid.uuid4())
    with open("/etc/rhn/rhn.conf", "a", encoding="utf8") as r:
        r.write("\n")
        r.write(f"server.susemanager.scc_backup_srv_usr = {uuid_num}\n")


def import_suma_gpg_keyring():

    result = subprocess.run(
        ["/usr/sbin/import-suma-build-keys"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        encoding="utf-8",
        check=False,
    )

    if result.returncode:
        sys.stdout.write("Failed to import SUSE Manager Build Keys\n")
    if result.stdout:
        sys.stdout.write(f"{result.stdout}\n")
    sys.stdout.flush()


def copy_ca():
    ca = "/etc/pki/trust/anchors/LOCAL-RHN-ORG-TRUSTED-SSL-CERT"
    salt_ca = "/usr/share/susemanager/salt/certs/RHN-ORG-TRUSTED-SSL-CERT"
    # Nothing to copy if the CA is already in place: same file (podman secret,
    # helm subPath) or same content
    if (
        os.path.exists(ca)
        and os.path.exists(salt_ca)
        and filecmp.cmp(ca, salt_ca, shallow=False)
    ):
        return

    result = subprocess.run(
        [
            "cp",
            ca,
            salt_ca,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        encoding="utf-8",
        check=False,
    )

    if result.returncode:
        sys.stdout.write("Failed to copy the CA certificate to the Salt Filesystem\n")
    if result.stdout:
        sys.stdout.write(f"{result.stdout}\n")
    sys.stdout.flush()


def change_billing_data_service():
    sysconf = "/etc/sysconfig/billing-data-service"
    content = []
    changed = False
    if os.path.exists(sysconf):
        with open(sysconf, "r", encoding="utf8") as f:
            for line in f:
                line = line.strip()
                if line == 'LISTEN="127.0.0.1"':
                    line = 'LISTEN="0.0.0.0"'
                    changed = True
                content.append(line)

        if not changed:
            sys.stdout.write("billing-data-service sysconfig file unchanged\n")
            return
        with open(sysconf, "w", encoding="utf8") as r:
            for line in content:
                r.write(f"{line}\n")
        sys.stdout.write("billing-data-service sysconfig: changed LISTEN address\n")


def init_dirs_and_perms():
    mount_point = "/var/spacewalk"
    with cfg_component("server") as CFG:
        mount_point = CFG.MOUNT_POINT
    if not mount_point:
        sys.stdout.write("Invalid mount point. Aborting!\n")
        sys.stdout.flush()
        sys.exit(1)

    # mount_point/systems dir with 775 wwwrun www
    system_dir = os.path.join(mount_point, "systems")
    if not os.path.exists(system_dir):
        try:
            os.makedirs(system_dir)
        except OSError as e:
            sys.stdout.write(f"Failed to create directory {system_dir}: {e}")
            sys.exit(1)

    shutil.chown(system_dir, "wwwrun", "www")
    os.chmod(system_dir, int("0775", 8))


def remove_product_name_overwrite():
    pattern = re.compile(r"^product_name\s*=.*$")
    with open("/etc/rhn/rhn.conf", "r+", encoding="utf8") as f:
        new_f = f.readlines()
        f.seek(0)
        for line in new_f:
            if not pattern.match(line.strip()):
                f.write(line)
        f.truncate()


def change_hostname():
    result = subprocess.run(
        ["/usr/bin/spacewalk-hostname-rename"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        encoding="utf-8",
        check=False,
    )

    if result.returncode:
        sys.stdout.write("Failed to rename the server\n")
    if result.stdout:
        sys.stdout.write(f"{result.stdout}\n")
    sys.stdout.flush()
    return result.returncode


def main():
    if sys.argv[1:] == ["--move-config-to-db"]:
        # called by spacewalk-startup-helper after the schema upgrade, which
        # creates the rhnConfiguration rows of newly moved keys
        move_config_to_db()
        return 0

    init_dirs_and_perms()
    check_and_configure_fips()
    exitCode = run_uyuni_configfiles_sync()
    init_scc_login()
    import_suma_gpg_keyring()
    copy_ca()
    hash_plain_text_passwords()
    rename_config_keys()
    change_billing_data_service()
    remove_product_name_overwrite()

    exitCode = max(change_hostname(), exitCode)
    return exitCode


if __name__ == "__main__":
    sys.exit(abs(main() or 0))
