def main():
    utils.check_login_user()

    # parse input option
    argv = [encode.convert_to_unicode(a) for a in sys.argv[1:]]
    args = get_parser().parse_args(argv)

    # read and check args
    kwargs = {}
    if args.name is not None:
        kwargs['name'] = args.name
    if args.metadata is not None:
        kwargs['metadata'] = args.metadata
    if args.description is not None:
        kwargs['description'] = args.description
    if args.file_name is not None:
        kwargs['file_name'] = args.file_name
    if args.fpga_image_id is not None:
        kwargs['fpga_image_id'] = args.fpga_image_id
    if args.image_id is not None:
        kwargs['image_id'] = args.image_id
    if args.page is not None:
        kwargs['page'] = args.page
    if args.size is not None:
        kwargs['size'] = args.size
    try:
        utils.check_param(**kwargs)
    except Exception as e:
        utils.exit('Error: %s' % encode.exception_to_unicode(e))

    # read and check config file
    config.read_config_and_verify()
    access_key = os.getenv('OS_ACCESS_KEY')
    secret_key = os.getenv('OS_SECRET_KEY')
    bucket_name = os.getenv('OS_BUCKET_NAME')
    region_id = os.getenv('OS_REGION_ID')
    domain_id = os.getenv('OS_DOMAIN_ID')
    project_id = os.getenv('OS_PROJECT_ID')
    obs_endpoint = os.getenv('OS_OBS_ENDPOINT')
    vpc_endpoint = os.getenv('OS_VPC_ENDPOINT')
    fis_endpoint = os.getenv('OS_FIS_ENDPOINT')

    try:
        # configure intranet dns of ecs
        config.configure_intranet_dns_ecs(region_id)

        # check bucket
        utils._check_bucket_acl_location(bucket_name, access_key, secret_key,
                                         obs_endpoint, region_id, domain_id)
        # check fis
        rest.fpga_image_relation_list(access_key, secret_key, project_id,
                                      region_id, fis_endpoint)
    except Exception as e:
        utils.exit('Error: %s' % encode.exception_to_unicode(e))

    if kwargs:
        print('fis argument(s) and config file are OK')
    else:
        print('fis config file is OK')
def do_configure(args):
    """Invoke interactive (re)configuration tool"""
    cur_conf = config.read_current_config()
    if args.dump:
        for key in ('OS_ACCESS_KEY', 'OS_SECRET_KEY', 'OS_BUCKET_NAME',
                    'OS_REGION_ID'):
            print("%s = %s" % (key, cur_conf.get(key, '')))
        return

    access_key_old = cur_conf.get('OS_ACCESS_KEY', '')
    secret_key_old = cur_conf.get('OS_SECRET_KEY', '')
    bucket_name_old = cur_conf.get('OS_BUCKET_NAME', '')
    region_id_old = cur_conf.get('OS_REGION_ID', '')
    configure_region_id = False

    try:
        print('Enter new values or accept defaults in brackets with Enter')

        # get region_id from ECS metadata
        print('\nGetting region_id from ECS metadata.')
        region_id = rest.get_region_id_from_metadata()
        if region_id:
            print('You are in region "%s".' % region_id)
        else:
            # configure region_id interactively when get it from ECS metadata failed
            configure_region_id = True
            print(
                '\n\033[31mNote: If an incorrect Region ID is used, the FPGA image registration and querying may succeed, but the FPGA loading will fail.\033[0m'
            )
            print('Choose the Region where you are located.')
            regions = config.endpoints.keys()
            print('Available Regions:')
            for i, region in enumerate(regions, 1):
                print('  (%d) %s' % (i, region))
            while True:
                region_id = raw_input('Region ID [%s]: ' %
                                      region_id_old).strip() or region_id_old
                if re.match(u'\d+$',
                            region_id) and 1 <= int(region_id) <= len(regions):
                    region_id = regions[int(region_id) - 1]
                    break
                elif region_id in regions:
                    break
                elif not region_id:
                    utils.print_err('Error: empty input')
                else:
                    utils.print_err('Error: "%s" is not a valid region' %
                                    region_id)

        obs_endpoint = config.get_endpoint(region_id, 'obs')
        iam_endpoint = config.get_endpoint(region_id, 'iam')
        vpc_endpoint = config.get_endpoint(region_id, 'vpc')
        fis_endpoint = config.get_endpoint(region_id, 'fis')

        # configure intranet dns of ecs
        config.configure_intranet_dns_ecs(region_id)

        # loop until access_key, secret_key are OK
        while True:
            try:
                print(
                    '\nAccess key and Secret key are your identifiers for FIS and OBS.'
                )
                while True:
                    access_key = raw_input(
                        'Access Key [%s]: ' %
                        access_key_old).strip() or access_key_old
                    if access_key:
                        break
                    else:
                        utils.print_err('Error: empty input')

                while True:
                    secret_key = raw_input(
                        'Secret Key [%s]: ' %
                        secret_key_old).strip() or secret_key_old
                    if secret_key:
                        break
                    else:
                        utils.print_err('Error: empty input')

                bucket_list = rest.get_bucket_list(access_key, secret_key,
                                                   obs_endpoint)
                project = rest.get_project(access_key, secret_key, region_id,
                                           iam_endpoint).get('projects', [])
                if len(project) >= 1:
                    domain_id = project[0].get('domain_id')
                    project_id = project[0].get('id')
                else:
                    raise FisException(
                        'You do NOT have project in "%s", \033[31mplease '
                        'choose another region and try again\033[0m' %
                        region_id)

                # break when access_key, secret_key are OK
                break
            except (FisException, RequestException) as e:
                msg = encode.exception_to_unicode(e)
                if 'InvalidAccessKeyId' in msg:
                    msg += ', \033[31mTips=Maybe your Access Key is invalid\033[0m'
                elif 'SignatureDoesNotMatch' in msg:
                    msg += ', \033[31mTips=Maybe your Secret Key is invalid\033[0m'
                utils.print_err('Error: %s' % msg)
                access_key_old = access_key
                secret_key_old = secret_key

        # loop until bucket_name is OK
        print('\nGetting all your available buckets in "%s".' % region_id)
        buckets = bucket_list.get('Buckets', {})
        bucket_list = buckets.get('Bucket', []) if isinstance(buckets,
                                                              dict) else []
        if not isinstance(bucket_list, list):
            bucket_list = [bucket_list]
        all_bucket = [
            bucket.get('Name') for bucket in bucket_list
            if isinstance(bucket, dict)
        ]
        available_bucket = [
            bucket for bucket in all_bucket
            if utils.is_bucket_valid(bucket, access_key, secret_key,
                                     obs_endpoint, region_id, domain_id)
        ]
        if available_bucket:
            print(
                '\nChoose or Create a Bucket for storing the FPGA images to be registered.'
            )
            print('Available Bucket(s):')
            for i, bucket in enumerate(available_bucket, 1):
                print('  (%d) %s' % (i, bucket))
            while True:
                bucket_name = raw_input(
                    'Bucket Name [%s]: ' %
                    bucket_name_old).strip() or bucket_name_old
                if re.match(u'\d+$', bucket_name) and 1 <= int(
                        bucket_name) <= len(available_bucket):
                    bucket_name = available_bucket[int(bucket_name) - 1]
                    break
                if bucket_name.startswith('!'):
                    bucket_name = bucket_name[1:]
                if (bucket_name in available_bucket
                        or _check_and_create_bucket(bucket_name, all_bucket,
                                                    access_key, secret_key,
                                                    region_id, obs_endpoint)):
                    break
        else:
            print(
                '\nCreate a Bucket for storing the FPGA images to be registered.'
            )
            while True:
                bucket_name = raw_input(
                    'Bucket Name [%s]: ' %
                    bucket_name_old).strip() or bucket_name_old
                if _check_and_create_bucket(bucket_name, all_bucket,
                                            access_key, secret_key, region_id,
                                            obs_endpoint):
                    break

        # configure intranet dns of vpc
        print('\nChecking private DNS of VPC.')
        config.configure_intranet_dns_vpc(access_key, secret_key, project_id,
                                          region_id, vpc_endpoint)

        # save new settings
        if not configure_region_id:
            print(
                '\nNew settings:\n  Access key: %s\n  Secret Key: %s\n  Bucket Name: %s'
                % (access_key, secret_key, bucket_name))
        else:
            print(
                '\nNew settings:\n  Region ID: %s\n  Access key: %s\n  Secret Key: %s\n  Bucket Name: %s'
                % (region_id, access_key, secret_key, bucket_name))
        save_option = raw_input('Save settings? [Y/n]: ').strip() or 'Y'
        if 'yes'.startswith(save_option.lower()):
            config.save_config(access_key, secret_key, bucket_name, region_id,
                               domain_id, project_id, obs_endpoint,
                               iam_endpoint, vpc_endpoint, fis_endpoint)
            print('Configuration saved to "%s".' %
                  os.path.expanduser(config.CONFIG_FILE))
        else:
            print('Changes were NOT saved.')
    except (KeyboardInterrupt, EOFError):
        exit()