# Copyright (c) 2020 VMware, Inc.  All rights reserved. -- VMware Confidential
# coding: utf-8

import logging
import os
from shutil import move

from wcpconfigure import LS_SPEC_FILE_PATH, register_with_ls


logger = logging.getLogger(__name__)


CHANGELOG = ["Updated registration of wcp with lookup service"]
_RPMNEW_EXT = '.rpmnew'
_RPMSAVE_EXT = '.rpmsave'
_LS_SPEC_FILE_PATH_NEW = LS_SPEC_FILE_PATH + _RPMNEW_EXT
_LS_SPEC_FILE_PATH_SAVE = LS_SPEC_FILE_PATH + _RPMSAVE_EXT


def update_ls_registration():
    """
    Update registration of WCP service with lookup service if there is a new
    lookup service spec available.
    """

    # We want to re-register with the original file, but if .rpmnew exists,
    # this means the original file was not updated after rpm upgrade, so we
    # simply replace original with .rpmnew
    if os.path.isfile(_LS_SPEC_FILE_PATH_NEW):
        move(_LS_SPEC_FILE_PATH_NEW, LS_SPEC_FILE_PATH)
    # If this file exists, this means the original file was replaced by the file
    # in rpm and previous version is backed up to this file, we simply remove it.
    if os.path.isfile(_LS_SPEC_FILE_PATH_SAVE):
        os.remove(_LS_SPEC_FILE_PATH_SAVE)

    try:
        register_with_ls(LS_SPEC_FILE_PATH, regOp='tryupgrade')
    except Exception as ex:
        logging.error("Failed to update WCP registration with lookup service; "
                      "%s", str(ex))
        raise
    logging.info("Successfully updated registration of WCP in lookup service")


def doPatchingWithDependencies():
    update_ls_registration()


def doPatchingWithoutDependencies():
    """
    doPatchingWithoutDependencies is executed before services that wcpsvc
    depends on are started. This patch requires lookup service to be running
    to update the wcp registration.
    """
    pass


def getChanges():
    return '%s: Changelog:\n%s' % (
        os.path.basename(__file__),
        '\n'.join(['* ' + line for line in CHANGELOG]))
