#!/usr/bin/python2
#
# 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

import OpenSSL

# disable sgmlop module
# it breaks rhn_check when loaded during xmlrpclib import
sys.modules['sgmlop'] = None

from up2date_client import getMethod
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 clientCaps
from up2date_client import capabilities
from up2date_client import rhncli, rhnserver

from rhn import SSL
from rhn import rhnLockfile
from rhn.i18n import bstr, sstr
from rhn.tb import raise_with_tb

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

if 'sgmlop' in sys.modules:
    del sys.modules['sgmlop']

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

# action version we understand
ACTION_VERSION = 2

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

# Actions that will ru
n each time we execute.
LOCAL_ACTIONS = [("packages.checkNeedUpdate", ("rhnsd=1",))]


class CheckCli(rhncli.RhnCli):

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

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

    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 = CheckCli.__get_server()

        CheckCli.__update_system_id()

        self.__run_remote_actions()
        CheckCli.__run_local_actions()

        s = rhnserver.RhnServer()
        if s.capabilities.hasCapability('staging_content', 1) and cfg['stagingContent'] != 0:
             self.__check_future_actions()

        sys.exit(0)

    def __get_action(self, status_report):
        try:
            action = self.server.queue.get(up2dateAuth.getSystemId(),
                ACTION_VERSION, status_report)

            return action
        except xmlrpclib.Fault:
            f = sys.exc_info()[1]
            if f.faultCode == -31:
                raise_with_tb(up2dateErrors.InsuffMgmntEntsError(f.faultString))
            else:
                print("Could not retrieve action item from server %s" % self.server)
                print("Error code: %d%s" % (f.faultCode, f.faultString))
            sys.exit(-1)
        # XXX: what if no SSL in socket?
        except SSL.socket_error:
            print("ERROR: SSL handshake to %s failed" % self.server)
            print("""
            This could signal that you are *NOT* talking to a server
            whose certificate was signed by a Certificate Authority
            listed in the %s file or that the
            RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert)
            sys.exit(-1)
        except socket.error:
            print("Could not retrieve action from %s.\n"\
                  "Possible networking problem?" % str(self.server))
            sys.exit(-1)
        except up2dateErrors.ServerCapabilityError:
            print(sys.exc_info()[1])
            sys.exit(1)
        except OpenSSL.SSL.Error:
            print("ERROR: SSL errors detected")
            print("%s" % sys.exc_info()[1])
            sys.exit(-1)

    def __query_future_actions(self, time_window):
        try:
            actions = self.server.queue.get_future_actions(up2dateAuth.getSystemId(),
                time_window)
            return actions
        except xmlrpclib.Fault:
            f = sys.exc_info()[1]
            if f.faultCode == -31:
                raise_with_tb(up2dateErrors.InsuffMgmntEntsError(f.faultString))
            else:
                print("Could not retrieve action item from server %s" % self.server)
                print("Error code: %d%s" % (f.faultCode, f.faultString))
            sys.exit(-1)
        # XXX: what if no SSL in socket?
        except SSL.socket_error:
            print("ERROR: SSL handshake to %s failed" % self.server)
            print("""
            This could signal that you are *NOT* talking to a server
            whose certificate was signed by a Certificate Authority
            listed in the %s file or that the
            RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert)
            sys.exit(-1)
        except socket.error:
            print("Could not retrieve action from %s.\n"\
                  "Possible networking problem?" % str(self.server))
            sys.exit(-1)
        except up2dateErrors.ServerCapabilityError:
            print(sys.exc_info()[1])
            sys.exit(1)
        except SSL.Error:
            print("ERROR: SSL errors detected")
            print("%s" % sys.exc_info()[1])
            sys.exit(-1)

    def __fetch_future_action(self, action):
        """ Fetch one specific action from rhnParent """
        # TODO
        pass

    def __check_future_actions(self):
        """ Retrieve scheduled actions and cache them if possible """
        time_window = cfg['stagingContentWindow'] or 24;
        actions = self.__query_future_actions(time_window)
        for action in actions:
            self.handle_action(action, cache_only=1)

    def __run_remote_actions(self):
        # the list of caps the client needs
        caps = capabilities.Capabilities()

        status_report = CheckCli.__build_status_report()

        action = self.__get_action(status_report)
        while action != "" and action != {}:
            self.__verify_server_capabilities(caps)

            if self.is_valid_action(action):
                try:
                    up2dateAuth.updateLoginInfo()
                except up2dateErrors.ServerCapabilityError:
                    print(sys.exc_info()[1])
                    sys.exit(1)
                self.handle_action(action)

            action = self.__get_action(status_report)

    def __verify_server_capabilities(self, caps):
        response_headers = self.server.get_response_headers()
        caps.populate(response_headers)
        # do we actually want to validte here?
        try:
            caps.validate()
        except up2dateErrors.ServerCapabilityError:
            print(sys.exc_info()[1])
            sys.exit(1)

    def __parse_action_data(self, action):
        """ Parse action data and returns (method, params) """
        data = action['action']
        parser, decoder = xmlrpclib.getparser()
        parser.feed(bstr(data))
        parser.close