#!/opt/cloudlinux/venv/bin/python3 -bb
import argparse
import subprocess, os
import pathlib

HOOKS_DIR = '/opt/cloudlinux/rhn_hooks/post.d'
JWT_TOKEN = '/etc/sysconfig/rhn/jwt.token'


def _is_ubuntu():
    return "ID=ubuntu" in open("/etc/os-release").read()


def _update_edition_user_file():
    """
    Save information about current edition in specific
    location available for users
    """
    if not os.path.exists('/usr/bin/cldetect') or not os.path.exists('/opt/cloudlinux/'):
        return

    p = subprocess.Popen(['/usr/bin/cldetect', '--detect-edition'],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if p.returncode == 0:
        with open('/opt/cloudlinux/cl_edition.tmp', 'wb') as f:
            f.write(stdout)
        os.rename('/opt/cloudlinux/cl_edition.tmp', '/opt/cloudlinux/cl_edition')
        os.chmod('/opt/cloudlinux/cl_edition', 0o644)


def _trigger_universal_hooks():
    """
    Discovers executable files in directory and triggers them all together
    Executable files are brought by different rpm packages, depending on which one
    requires the action
    """
    if not os.path.exists(HOOKS_DIR):
        return

    hooks = [os.path.join(HOOKS_DIR, f) for f in os.listdir(HOOKS_DIR)
             if os.path.isfile(os.path.join(HOOKS_DIR, f))]

    for hook in hooks:
        process = subprocess.Popen([hook],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()


def _create_symlink(target, linkpath, force=False):
    """
    Creates symlink. If force is set to True,
    it will overwrite existing symlink or file
    """
    target = pathlib.Path(target)
    linkpath = pathlib.Path(linkpath)

    # if already the same, ignore
    if linkpath.resolve() == target.resolve():
        return

    # remove existing file or link
    if force and (linkpath.exists() or linkpath.is_symlink()):
        linkpath.unlink()

    linkpath.symlink_to(target)


def _run_edition_change_check():
    # run interactively
    subprocess.run(['cloudlinux-edition-watcher', 'check'])


def _create_repo_auth_symlinks():
    """
    Create symlinks for els repos authentication
    """
    _create_symlink(JWT_TOKEN, '/etc/dnf/vars/phpelstoken', force=True)
    _create_symlink(JWT_TOKEN, '/etc/dnf/vars/altpythonelstoken', force=True)
    _create_symlink(JWT_TOKEN, '/etc/dnf/vars/altrubyelstoken', force=True)
    _create_symlink(JWT_TOKEN, '/etc/dnf/vars/altnodejselstoken', force=True)


def _create_repo_auth_conf():
    """
    Create alt-repo.conf file for els repos authentication on Ubuntu
    """
    token = pathlib.Path(JWT_TOKEN).read_text().strip()
    conf = f"machine repo.alt.tuxcare.com\nlogin {token}"
    auth_file = pathlib.Path("/etc/apt/auth.conf.d/alt-repo.conf")
    auth_file.write_text(conf)
    auth_file.chmod(0o600)


def main(args):
    """
    You add your other actions here, but don't forget to handle errors.
    """
    _update_edition_user_file()
    if _is_ubuntu():
        _create_repo_auth_conf()
    else:
        _create_repo_auth_symlinks()
    if args.allow_transition:
        _run_edition_change_check()
    _trigger_universal_hooks()


if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument('--allow-transition', action='store_true', default=False)

    main(args=parser.parse_args())
