#!/usr/bin/python

from invirt.config import structs as config
from subprocess import Popen, call, PIPE
import tempfile
import os
import sys
import shutil

def main():
    call(['kinit', '-k', 'daemon/%s' % config.web.hostname])
    
    shutil.copy('/usr/share/invirt-vnc-client/VncViewer.src.jar',
                '/usr/share/invirt-vnc-client/VncViewer.jar')
    
    temp_dir = tempfile.mkdtemp()
    keystore = os.path.join(temp_dir, 'trust.store')
    for host in config.hosts:
        cert = Popen(['remctl', config.remote.hostname, 'web', 'vnccert', host.hostname],
                     stdout=PIPE)
        cert.wait()
        call(['keytool', '-import', '-noprompt', '-alias', host.hostname,
              '-keystore', keystore, '-storepass', 'foobar'],
             stdin=cert.stdout)
    
    call(['jar', 'uf', '/usr/share/invirt-vnc-client/VncViewer.jar',
          '-C', temp_dir, 'trust.store'])
    
    shutil.rmtree(temp_dir)

if __name__ == '__main__':
    sys.exit(main())
