#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2014 Red Hat, Inc.
#
# Licensed to you under the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  See the files README and
# LICENSE_GPL_v2 which accompany this distribution.
#
import logging
import subprocess
import sys
import time

from xml.sax import saxutils

_log_file = '/var/log/vdsm-reg/vds_bootstrap_upgrade.%s.log' % \
    time.strftime("%Y%m%d_%H%M%S")

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-8s %(message)s',
    datefmt='%a, %d %b %Y %H:%M:%S',
    filename=_log_file,
    filemode='w'
)


def _output(component, message=None, success=True):
    """
    Encapsulate the message into XML for Engine

    Args:
    success: True (OK) or False (FAIL)
    component: OK, FAIL or RHEV_INSTALL
    message: message to be encapsulate into XML format or None to omit
    """

    msg = "<BSTRAP component=%s status=%s %s/>\n" % (
        saxutils.quoteattr(component),
        saxutils.quoteattr("OK" if success else "FAIL"),
        "" if message is None else "message=%s" % saxutils.quoteattr(message)
    )

    sys.stdout.write(msg)
    sys.stdout.flush()
    logging.debug(msg)


def main():
    upgrade_tool = subprocess.Popen(
        [
            "ovirt-node-upgrade",
            "--iso=/data/updates/ovirt-node-image.iso",
            "--reboot=1"
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=False
    )

    # ovirt-upgrade uses logger to display the messages during the
    # upgrade process which by default is stderr.
    # To get the messages async we should read stderr when triggering
    # the upgrade since the tool uses subprocess.Popen() that waits
    # the command terminates.
    while upgrade_tool.poll() is None:
        line = upgrade_tool.stdout.readline()
        if line:
            _output(
                component='ovirt-node-upgrade',
                message=line
            )

    if upgrade_tool.returncode == 0:
        _output(
            component='ovirt-node-upgrade',
            message='Upgraded Succeeded. Rebooting'
        )

        _output(
            component='RHEV_INSTALL'
        )
    else:
        _output(
            component='ovirt-node-upgrade',
            message='Upgraded Failed',
            success=False
        )

        _output(
            component='RHEV_INSTALL',
            success=False
        )

    return upgrade_tool.returncode

if __name__ == "__main__":
    sys.exit(main())
