#!/usr/bin/python3
#
# Python client for checking periodically for posted actions
# on the Spacewalk servers.
#
# Copyright (c) 2000--2018 Red Hat, Inc.
#
# 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.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.

import base64
import os
import sys
import socket

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

from up2date_client import up2dateErrors
from up2date_client import up2dateAuth
from up2date_client import up2dateLog
from up2date_client import rpcServer
from up2date_client import config
from up2date_client import rhncli
from up2date_client import rhnreg

from rhn import rhnLockfile
from rhn.i18n import sstr

try: # python2
    import xmlrpclib
except ImportError: # python3
    import xmlrpc.client as xmlrpclib
    long = int

cfg = config.initUp2dateConfig()
log = up2dateLog.initLog()

# lock file to check if we're disabled at the server's request
DISABLE_FILE = "/etc/sysconfig/rhn/disable"


class CheckCli(rhncli.RhnCli):

    def __init__(self):
        super(CheckCli, self).__init__()

        self.rhns_ca_cert = cfg['sslCACert']
        self.server = None

        self.optparser.add_option(
            '--allow-transition', action="store_true",
            default=False, help=_("Allow automatic edition transition")),

    def main(self):
        """ Process all the actions we have in the queue. """
        CheckCli.__check_instance_lock()
        CheckCli.__check_rhn_disabled()
        CheckCli.__check_has_system_id()

        self.server = rpcServer.getServer()

        self.__update_system_id()

        self.__login()

        sys.exit(0)

    def __login(self):
        up2dateAuth.login()

    def __update_system_id(self):
        try:
            up2dateAuth.maybeUpdateVersion()
            system_id_file_content = up2dateAuth.getSystemId()
            # update JWT token
            rhnreg.getAndWriteJWTTokenToFile(
                system_id_file_content,
                allowTransition=self.options.allow_transition)
        except up2dateErrors.CommunicationError:
            print(sys.exc_info()[1])
            sys.exit(1)


    @staticmethod
    def __check_rhn_disabled():
        """ If we're disabled, go down (almost) quietly. """
        if os.path.exists(DISABLE_FILE):
            print("RHN service is disabled. Check %s" % DISABLE_FILE)
            sys.exit(0)

    @staticmethod
    def __check_has_system_id():
        """ Retrieve the system_id. This is required. """
        if not up2dateAuth.getSystemId():
            print("ERROR: unable to read system id.")
            sys.exit(-1)

    @staticmethod
    def __check_instance_lock():
        lock = None
        try:
            lock = rhnLockfile.Lockfile('/var/run/rhn_check.pid')
        except rhnLockfile.LockfileLockedException:
            sys.stderr.write(sstr(_("Attempting to run more than one instance of rhn_check. Exiting.\n")))
            sys.exit(0)

if __name__ == "__main__":
    cli = CheckCli()
    cli.run()
