#!/opt/duoauthproxy/usr/local/bin/python3 -s
#
# Copyright (c) 2023 Duo Security
# All Rights Reserved
#

# This import _must_ be first
import _fipscustomize # noqa: F401, isort:skip

import os
import shutil
from sys import exit
from datetime import datetime
from duoauthproxy.lib import path_util, config_provider


def script_parser():
    root = path_util.get_home_dir()
    config_filename = os.path.join(root, "conf", "authproxy.cfg")

    # check what sections are radius_server_iframe if the config has a radius_server_iframe section
    try:
        provider_config = config_provider.get_config(config_filename)
    except PermissionError as ex:
        print(ex)
        print("Operation not permitted. Please run the script as a superuser")
        exit(1)
    all_sections = provider_config.get_all_sections()

    iframe_keys = []
    for section_name, section in all_sections.items():
        section_values = section.items()
        for v in section_values:
            if "type" in v:
                iframe_keys.append(section_name)
                break

    # if the list of sections is empty, there is no radius_server_iframe section
    if not iframe_keys :
        print("There is no radius_server_iframe section in your config")
        exit(0)

    # check each line of the config
    # if it starts with "type", it's not copied over to the new file
    # otherwise, the line is copied over,
    # if it contains [radius_server_iframe, it's replaced with auto, leaving the config section name additions
    new_config = os.path.join(root, "conf", "new_config.txt")

    radius_server_auto_section_names = get_config_radius_server_auto_names(all_sections)

    try:
        with open(config_filename, "rt") as fin:
            with open(new_config, "wt") as fout:
                for line in fin:
                    if line.startswith("type"):
                        # ignore the type option
                        continue
                    elif line.startswith("[radius_server_iframe"):
                        # replace the iframe section with auto section
                        next_radius_server_auto_name, radius_server_auto_section_names = get_next_auto_section_name(radius_server_auto_section_names)
                        fout.write("".join(("[", next_radius_server_auto_name , "]")))
                        fout.write("\n")
                    else:
                        fout.write(line)
    except FileNotFoundError as ex:
        print(ex)
        print("The configuration file could not be found")
        exit(1)

    # remove the previous config and rename the new file to the new config
    current_datetime = str(datetime.now().strftime("%Y-%m-%dT%H%M%S"))
    timing = "authproxy-backup-" + current_datetime + ".cfg"
    backup_config = os.path.join(root, "conf", timing)

    try:
        shutil.copyfile(config_filename, backup_config)
    except IOError as ex:
        print(ex)
        print("Backup configuration could not be made")
        exit(1)

    try:
        os.remove(config_filename)
        os.rename(new_config, config_filename)
        print("Script was successful")
    except PermissionError as ex:
        print(ex)
        print("Operation not permitted. Please run the script as a superuser")
        exit(1)
    except OSError as ex:
        print(ex)
        exit(1)
    return


def get_config_radius_server_auto_names(all_sections):
    radius_server_auto_section_names = []
    for section_name, _ in all_sections.items():
        if section_name.startswith("radius_server_auto"):
            radius_server_auto_section_names.append(section_name)
    return radius_server_auto_section_names


def get_next_auto_section_name(auto_section_names):
    base_auto_server_name = "radius_server_auto"

    SECTION_SUFFIX = 0
    next_auto_server_name = base_auto_server_name
    while next_auto_server_name in auto_section_names:
        SECTION_SUFFIX += 1
        next_auto_server_name = "".join((base_auto_server_name, str(SECTION_SUFFIX)))
    auto_section_names.append(next_auto_server_name)

    return next_auto_server_name, auto_section_names


if __name__ == "__main__":
    script_parser()
