#!/usr/bin/env python
##
#
# Vaisala software source code file
#
# Copyright (c) Vaisala Oyj 2015. All rights reserved.
#
##
"""
Wrapper tool for radar site setup for basemaps.
"""
import ConfigParser
import argparse
import json
import logging
import os.path
import subprocess
import sys


logger = logging.getLogger('rsw-basemap-site-setup')


def ensure_good_environment(config_dir):
    """Adds the default VAISALA_RADARSW_CONFIG_DIR environment variable if not
    already present."""
    key = "VAISALA_RADARSW_CONFIG_DIR"

    if key in os.environ and os.environ[key] == config_dir:
        return

    os.environ[key] = config_dir
    logger.info(u"'{}' => '{}'".format(key, os.environ[key]))


def extract_socket_server_host(file_path):
    """Extracts the data source password from a file and does no error
    handling. User is expected to handle ConfigParser thrown errors.

    See https://docs.python.org/2.7/library/configparser.html#ConfigParser.Error
    for more information.
    """
    config = ConfigParser.SafeConfigParser()
    config.read(file_path)
    return config.get("IRIS_SOCKET_SERVER", "iris.socket.server.host")


def main(args):
    def setup_logging(debug_enabled):
        root = logging.getLogger()
        if debug_enabled:
            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        root.addHandler(ch)
    setup_logging(args.debug)
    ensure_good_environment(args.config_dir)

    geoserver_settings = json.loads(subprocess.check_output(['rsw-geoserver-password-tool', 'show']))
    logger.debug(u"GeoServer settings {} loaded.".format(', '.join(geoserver_settings.keys())))

    logger.info(u"Fetching radar centers from IRIS socket server...")
    get_centers_command = ["/usr/vaisala/radarsw/configuration/bin/configure-geoserver",
                           "get_centers", "-s", args.socket_server]
    subprocess.check_call(get_centers_command)
    logger.info(u"Radar centers done.")

    geoserver_config_command = ["/usr/vaisala/radarsw/configuration/bin/configure-geoserver",
                                "configure",
                                "-url", args.geoserver_config_url,
                                "--password", geoserver_settings['admin_password'],
                                "--username", "admin"]
    logger.info("Configuring GeoServer with radar center specific projections...")
    subprocess.check_call(geoserver_config_command)
    logger.info("GeoServer configured with radar center specific projections.")

    logger.info(u"IRIS Vision is now configured with new radar centers.")
    logger.info(u"Please restart the service 'vaisala-radarsw-webapp' to take changes into account.")


if __name__ == "__main__":
    default_config_dir = os.environ.get("VAISALA_RADARSW_CONFIG_DIR",
                                        '/etc/vaisala/radarsw/configuration')
    socket_server_host = None
    try:
        socket_server_host = extract_socket_server_host(
            os.path.join(default_config_dir, "vsoweb-override.ini"))
    except:
        pass

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    if socket_server_host is None:
        parser.add_argument("--socket-server", dest="socket_server",
                            help="IRIS socket server address.", required=True)
    else:
        parser.add_argument("--socket-server", dest="socket_server",
                            help="IRIS socket server address.", required=False,
                            default=socket_server_host)

    parser.add_argument("--geoserver-config-url", dest="geoserver_config_url",
                        help="GeoServer configuration URL.",
                        default="http://localhost:34180/geoserver",
                        metavar="URL")
    parser.add_argument("-c", "--config-dir", dest="config_dir",
                        default=default_config_dir, metavar="DIRECTORY")
    parser.add_argument("-d", "--debug", dest="debug", action="store_true", help="Enable debug logging.")
    args = parser.parse_args()
    main(args)
