#!/usr/bin/python3

# Copyright (c) 2021, SUSE LLC, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
import logging
import os
import requests
import subprocess
import sys

import cloudregister.registerutils as utils

CACHE_LICENSE_PATH = os.path.join(utils.get_state_dir(), 'cached_license')


def update_license_cache(license_type):
    """Update the cache to track the license type"""
    with open(CACHE_LICENSE_PATH, 'w+') as cached_license:
        cached_license.write(license_type)


def has_license_changed(license_type):
    """Check license type changes against metadata info"""
    try:
        with open(CACHE_LICENSE_PATH, 'r') as cached_license:
            old_license = cached_license.read()
            return license_type != old_license
    except FileNotFoundError:
        update_license_cache(license_type)


def get_license_type():
    proxies = {
        'http': None,
        'https': None
    }
    headers = {'Metadata': 'true'}
    imds_server_base_url = 'http://169.254.169.254'

    instance_api_version = '2021-03-01'
    instance_endpoint = '{base_url}/metadata/instance/compute/licenseType?' \
        'api-version={api_version}&format=text'.format(
            base_url=imds_server_base_url,
            api_version=instance_api_version
        )

    res = requests.get(instance_endpoint, headers=headers, proxies=proxies)

    if res.status_code != 200:
        logging.error('Unable to obtain instance metadata')
        sys.exit(1)

    return res.text

# TODO use utils.exec_subprocess()
def run_command(command):
    logging.info('Calling {}'.format(command))
    try:
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            env=os.environ
        )
    except Exception as issue:
        logging.error(
            'EXEC: Exception running command {0} with issue: {1}: {2}'.format(
                ' '.join(command), type(issue).__name__, issue
            )
        )
        sys.exit(1)

    output, error = process.communicate()
    if process.returncode != 0 and error.decode():
        logging.error(
            'EXEC: Failed with stderr: {0}, stdout: {1}'.format(
                error.decode(), output.decode()
            )
        )
        sys.exit(1)
    output = output.decode()
    output = output.replace('\n', '')
    return output


utils.start_logging()
service_name = 'guestregister'
license_type = get_license_type()

if ('BYOS' in license_type and has_license_changed(license_type) and
    not utils.uses_rmt_as_scc_proxy()):
    run_command(['registercloudguest', '--clean'])
    run_command(['systemctl', 'disable', service_name])
    update_license_cache(license_type)
elif license_type and 'BYOS' not in license_type:
    # if no license type, system could be a BYOS without AHB
    # or PAYG without AHB
    update_server = utils.get_smt()
    if update_server:
        if (not has_license_changed(license_type) and
            utils.is_registered(update_server.get_FQDN())):
            sys.exit(0)
        update_license_cache(license_type)
        update_server = None
    if not update_server:
        run_command(['registercloudguest', '--force-new'])
        run_command(['systemctl', 'enable', service_name])
