#!/usr/bin/env python3

# ------------------------------------------------------------------------
# Copyright 2020 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------

""" Log into a container running in an OpenShift cluster """

# Global modules

import logging
import os
import sys

# Local modules

from modules.args    import (
    getCommonArgsParser,
    addArgFlavor,
    addArgNws4InstanceType
)
from modules.command import CmdShell
from modules.config  import getConfig
from modules.logger  import setupLogging
from modules.tools   import ocLogin

# Functions


def _getArgs():
    """ Get command line arguments """
    parser = getCommonArgsParser(
        'Log into a container running in an OpenShift cluster'
    )

    addArgFlavor(parser, ('nws4', 'hdb'), False)
    addArgNws4InstanceType(parser, ('di', 'ascs'), False)

    return parser.parse_args()


def _getPodName(config):
    """ Get the name of the pod in which our current deployment runs """
    return CmdShell().run(
        'oc get pods'
        + f' --selector="app=soos-{config.flavor.nws4.sid.lower()}"'
        + ' -o template --template "{{range .items}}{{.metadata.name}}{{end}}"'
    ).out


def _containerLogin(args, config):
    """ Log into running container of given flavor and instance type """

    podName = _getPodName(config)

    if args.flavor == 'hdb':
        containerName = config.flavor.hdb.containerName
    elif args.flavor == 'nws4':
        containerName = getattr(config.flavor.nws4, args.nws4_instance_type).containerName
    else:
        logging.error(f"Unexpected flavor '{args.flavor}'")
        sys.exit(1)

    print(f"Logging into container '{containerName}' of pod '{podName}'", file=sys.stderr)

    os.execlp('oc', 'oc', 'exec', '-it', podName, '-c', containerName, 'bash')

# ----------------------------------------------------------------------


def _main():
    """ Main function """

    args = _getArgs()

    setupLogging(args)

    config = getConfig(args.config_file, True)

    ocLogin(config)

    _containerLogin(args, config)

# ----------------------------------------------------------------------


if __name__ == '__main__':
    _main()
    sys.exit(0)
