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

import os
import sys
import optparse
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('--irodshost', dest='irods_host',
                      help="host which will host the new storage resource")
    parser.add_option('--storagepath', '--vaultpath', dest='vault_path',
                      help="path (relative to data server) where iRODS files should be stored")
    parser.add_option('--resourcename', dest='resc_name',
                      help="name for the storage resource in the zone")
    parser.add_option('--fabfile', dest='fabfile',
                      help="location of the fabfile to use for setup tasks")
    parser.add_option('--add', action='store_true', default=False,
                      help="add a new resource from iRODS host")
    parser.add_option('--remove', action='store_true', default=False,
                      help="remove a resource from iRODS")
    options, args = parser.parse_args()


    if ((not options.add and not options.remove)
        or (options.add and options.remove)):
        print('Must specify one of --add or --remove.')
        sys.exit(1)


    if not options.irods_host:
        print('%s requires the --irodshost option.' % (sys.argv[0],))
        sys.exit(1)
    else:
        if options.irods_host == 'localhost': options.irods_host = ''
        env.irods_host = socket.getfqdn(options.irods_host)

        
    if options.remove:
        if not options.resc_name:
            print('Remove operation requires --resourcename option.')
            sys.exit(1)
        env.resc_name = options.resc_name

    elif options.add:
        if not options.vault_path or not options.resc_name:
            print('Add requires both --storagepath and --resourcename must be provided.')
            sys.exit(1)
        env.vault_path = options.vault_path
        env.resc_name = options.resc_name


    env.hosts = [ env.irods_host, ]

    try:
        if options.add:
            execute(ids.fabfile.manage.add_resource)
        else:
            execute(ids.fabfile.manage.remove_resource)
    finally:
        fabric.network.disconnect_all()

    sys.exit(0)
