import sys
import os

import authentic.publisher as publisher

def lock(args):
    import authentic

    pub = publisher.AuthenticPublisher.create_publisher()

    if '--help' in args:
        print """Usage: authenticctl.py lock [...]'

Examples:
  authenticctl.py lock idp --message "Disabled for demo purpose"
  authenticctl.py lock --unlock idp --message "Disabled for demo purpose"
  authenticctl.py lock sp/http-authentic.example.com-liberty-metadata/ \\
      --message "Disabled for demo purpose"
  authenticctl.py lock --lock --identity 1
"""
        sys.exit(1)


    if '--vhost' in args:
        idx = args.index('--vhost')
        pub.app_dir = os.path.join(pub.app_dir, args[idx+1])
        del args[idx]
        del args[idx]
    pub.set_config()

    if '--display' in args:
        import pprint
        pprint.pprint(pub.cfg)
        sys.exit(0)

    lock = True
    if '--unlock' in args:
        lock = False 
        args.remove('--unlock')

    if '--message' in args:
        idx = args.index('--message')
        message = args[idx+1]
    else:
        message = 'configuration locked'

    if '--identity' in args:
        idx = args.index('--identity')
        identity_id = args[idx+1]
        import authentic.identities
        identity = pub.get_store().get_identity(identity_id)
        identity.locked_down = lock
        pub.get_store().save(identity)
        sys.exit(0)
    

    for k in args:
        d = pub.cfg
        for v in k.split('/'):
            d = d[v]
        if lock:
            d['locked'] = message
        else:
            del d['locked']

    pub.write_cfg()
