#!/usr/bin/env python

#
# Copyright 2021 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""
Patch script that does the following:
Removes CREATEDB privilege from the lvcm user. It is done here as it needs root
access

"""
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
from patch2 import VLCM_DB_PROPERTIES, PSQL, readPropertiesFile

logger = logging.getLogger(__name__)

def doPatching(ctx):
    logging.info("Start removing CREATEDB privilege from vlcm db user")
    try:
        logging.info("Reading VLCM properties")
        prop = readPropertiesFile()

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

        logging.info("Successfully removed CREATEDB privilege from vlcm db user.")
    except Exception as e:
        errorStr = "Faield to remove CREATEDB privilege from vlcm db user. "\
                   "Exception: \n%s" % e
        logging.error(errorStr)
        raise InternalError(errorStr)

