#!/usr/bin/env python
'''Prototype export misconversion fixup script for bad 7.2->8.0 upgrades'''

import sys
import isi.config.tardis as tardis
from optparse import OptionParser

def get_all_nfs_cfgs():
    '''NFS tardis namespaces all start with nfs_config_zone_'''
    return [ns for ns in tardis.list_namespaces() if ns.startswith('nfs_config_zone_')]

def repair_prototype_for_namespace(namespace_name, force=False, clean=False):
    '''Prototype export key should be 'exports_-3'. In a bad upgrade, it will
    actually be keyed under 'exports_-003'''

    print 'Checking prototype export for namespace {0}'.format(namespace_name)
    namespace = tardis.Namespace(namespace_name)
    bad_prototype = namespace.get_regexp('exports_-003')
    good_prototype = namespace.get_regexp('exports_-3')

    if (len(bad_prototype) > 0):
        print "Found broken prototype export."
        if not force and not clean:
            print 'Re-run with --force to repair by overwriting the current prototype '\
                'with the pre-upgrade copy.'
            print 'Re-run with --clean to repair by removing the broken prototype and '\
                'continue using currently defined prototype.'
        if force:
            print 'Overwriting prototype with pre-upgrade value...'
            namespace.sync(good_prototype)
            good_prototype['exports_-3'] = bad_prototype['exports_-003']
            namespace.update(good_prototype)
        if force or clean:
            print 'Removing bad prototype...'
            namespace.sync(bad_prototype)
            namespace.remove(bad_prototype)
    else:
        print "Prototype export is OK."

    namespace.close()

if __name__ == '__main__':
    parser = OptionParser(usage="Usage: %prog [options]\n\n"
                          "Tool for repairing NFS prototype export following a 7.2->8.0 upgrade.")
    parser.add_option("-f", "--force", dest="force", action="store_true",
        default=False,
        help="Actually overwrite the prototype export with the old copy.")
    parser.add_option("-c", "--clean", dest="clean", action="store_true",
        default=False,
        help="Just remove the broken prototype.")

    (options, args) = parser.parse_args()

    for namespace_name in get_all_nfs_cfgs():
        repair_prototype_for_namespace(namespace_name, options.force, options.clean)

    print 'Done.'
    sys.exit(0)
