#!/usr/bin/env python

#
# Copyright 2019 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Patch script that does the following:
Update registration to pick new metadata

"""
import logging
import os
import sys
import configparser
import io
import subprocess

from l10n import msgMetadata as _T, localizedString as _ # pylint: disable=E0401
from transport import getCommandExitCode # pylint: disable=E0401
from transport.local import LocalOperationsManager # pylint: disable=E0401
from patch_errors import UserError, InternalError


VLCM_DB_PROPERTIES = "/etc/vmware-vlcm/vlcm_db/vlcm.properties"
PSQL = '/opt/vmware/vpostgres/current/bin/psql'

logger = logging.getLogger(__name__)

#Loads the properties file
def readPropertiesFile(configFile=VLCM_DB_PROPERTIES):
    with open(configFile) as f:
        config = io.StringIO()
        config.write('[default]\n')
        config.write(f.read().replace('%', '%%'))
        config.seek(0, os.SEEK_SET)
        cp = configparser.ConfigParser()
        cp.readfp(config)

        return dict(cp.items('default'))

def doPatching(ctx):
    logging.info("Start granting the pg_monitor role to vlcm db user")
    try:
        logging.info("Reading VLCM properties")
        prop = readPropertiesFile()

        logging.info("Executing grant role command")
        cmd = [PSQL, '-U',  'postgres', '-d', 'VCDB', '-c', 'GRANT pg_monitor TO {};'.format(prop.get("username"))]
        exitCode = getCommandExitCode(LocalOperationsManager(), cmd)
        if exitCode:
            cause = _(_T('vlcm.database.monitor.role.error', 'Failed to update role permissions for vlcm database user.'))
            raise UserError(cause=cause)

        logging.info("Successfully granted pg_monitor role to vlcm db user.")
    except Exception as e:
        errorStr = "Faield to grant pg_monitor role to vlcm db user. "\
                   "Exception: \n%s" % e
        logging.error(errorStr)
        raise InternalError(errorStr)
