#!/usr/bin/env python
# -*- python -*-

import os
import sys
import optparse
import readline
import getpass
import socket
import subprocess
import fabric.network
from fabric.api import env, execute

import ids.fabfile

if __name__ == '__main__':

    parser = optparse.OptionParser()
    parser.add_option('--irodszone', '--zonename', dest='irods_zone',
                      help="name of the new zone")
    parser.add_option('--icathost', dest='icat_host',
                      help="FQDN of the new ICAT host (default is this host)")
    parser.add_option('--irodsuser', '--user', dest='irods_user',
                      help="username of the iRODS administrative user")
    parser.add_option('--irodspassword', '--pass', dest='irods_pass',
                      help="password for the iRODS administrative user")
    parser.add_option('--dbname', dest='db_name', default='icat',
                      help="name of the ICAT database (default is 'icat')")
    parser.add_option('--dbhost', dest='db_host', default='localhost',
                      help="ICAT database host (default is 'localhost')")
    parser.add_option('--dbuser', dest='db_user',
                      help="username to connect to the database instance (default is the same as irodsuser)")
    parser.add_option('--dbpass', dest='db_pass',
                      help="password to connect to the database instance (default is the same as irodspass)")

    parser.add_option('--fabuser', dest='fabuser',
                      help="user to connect to remote machine as. Default is calling user.")
    parser.add_option('--no-prompt', action='store_false', dest="prompt", default=True,
                      help="don't prompt for parameter values not provided via command-line options")
    options, args = parser.parse_args()


    # if prompting is turned off, exit if required options (i.e. those without
    # a reasonable default) are not provided
    if not options.prompt:
        if (not options.irods_zone or not options.icat_host
            or not options.irods_user or not options.irods_pass):
            print('You must provide values for zone, and for iRODS admin username and password')
            sys.exit(1)


    # check provided options, and prompt for those that are missing (and don't have defaults)
    while not options.irods_zone:
        options.irods_zone = raw_input('Enter the name of the new iRODS zone: ')
        if not options.irods_zone:
            print('You must provide an iRODS zone name. There is no default.')

    while not options.icat_host:
        options.icat_host = raw_input('Enter the name of the ICAT server for zone %s: '
                                      % (options.irods_zone,))
        if not options.icat_host:
            print('You must provide the ICAT server name. There is no default.')

    while not options.irods_user:
        options.irods_user = raw_input('Enter the user name for the iRODS administrative user: ')
        if not options.irods_user:
            print('You must provide the iRODS admin user name. There is no default.')

    while not options.irods_pass:
        tmp_pass1 = getpass.getpass('Enter the password for the iRODS administrative user: ')
        if not tmp_pass1:
            print('You cannot use an empty password.')
        tmp_pass2 = getpass.getpass('Enter the password again for verification           : ')
        if tmp_pass1 != tmp_pass2:
            print("Passwords don't match. Try again.")
        else:
            options.irods_pass = tmp_pass1


    # if database options aren't set, use reasonable defaults
    if not options.db_name: options.db_name = 'icat'
    if not options.db_host: options.db_host = 'localhost'
    if not options.db_user: options.db_user = options.irods_user
    if not options.db_pass: options.db_pass = options.irods_pass


    # resolve 'localhost' to a FQDN
    if options.icat_host == 'localhost':
        options.icat_host = socket.getfqdn()


    # set up the fabric environment 
    env.irods_zone = options.irods_zone
    env.icat_host = options.icat_host
    env.irods_user = options.irods_user
    env.irods_pass = options.irods_pass
    env.db_name = options.db_name
    env.db_host = options.db_host
    env.db_user = options.db_user
    env.db_pass = options.db_pass
    if options.fabuser:
        env.user = options.fabuser

    env.hosts = [ options.icat_host, ]

    try:
        execute(ids.fabfile.setup_zone)
    finally:
        fabric.network.disconnect_all()

    sys.exit(0)
