#!/usr/bin/env python
'''
Create or modify the tios configuration file administrator entries interactively.
'''
from tios import environments
import getpass
import argparse
import sys

if sys.version_info[0] == 2:
    input = raw_input

parser = argparse.ArgumentParser(description='Create or modify administrator data in the *tios* configuration file')
parser.add_argument('--url', help='URL of mongo database')
parser.add_argument('--port', help='port for mongo database')
parser.add_argument('--admin', help='administrator username')
parser.add_argument('--passwd', help='administrator password')

args = parser.parse_args()

tios_env = environments.load_mongo_env(authenticate=False)

for key in ['DB_URL', 'DB_COLLECTION', 'DB_ADMINISTRATOR', 'DB_ADMIN_PWD']:
    if not key in tios_env:
        tios_env[key] = ''

if not 'DB_NAME' is tios_env:
    tios_env['DB_NAME'] = 'tios'

if not 'DB_PORT' is tios_env:
    tios_env['DB_PORT'] = 27017

if not args.url:
    response = input("Database URL ({}):".format(tios_env['DB_URL']))
    if response != "":
        tios_env['DB_URL'] = response
else:
    tios_env['DB_URL'] = args.url

if not args.port:
    response = input("Database Port ({}):".format(tios_env['DB_PORT']))
    if response != "":
        tios_env['DB_PORT'] = response
else:
    tios_env['DB_PORT'] = args.port

if not args.admin:
    response = input("Admin username ({}):".format(tios_env['DB_ADMINISTRATOR']))
    if response != "":
        tios_env['DB_ADMINISTRATOR'] = response
else:
    tios_env['DB_ADMINISTRATOR'] = args.admin

if not args.passwd:
    response = getpass.getpass("Admin password (hit return to leave unchanged):")
    if response != "":
        tios_env['DB_ADMIN_PWD'] = response
else:
    tios_env['DB_ADMIN_PWD'] = args.passwd


tios_env = environments.load_mongo_env(source=tios_env, authenticate=True, administrator=True)
environments.save_mongo_env(tios_env)
