"""
Functions to perform remctls.
"""

from invirt.common import CodeError
import subprocess
import sys
from socket import getfqdn

def kinit(principal=None, keytab=None):
    """Kinit with a given username and keytab"""
    if principal is None:
        principal = 'daemon/' + getfqdn()
    if keytab is None:
        keytab = '/etc/invirt/keytab'
    p = subprocess.Popen(['kinit', "-k", "-t", keytab, principal],
                         stderr=subprocess.PIPE)
    e = p.wait()
    if e:
        raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))

def checkKinit(principal=None, keytab=None):
    """If we lack tickets, kinit."""
    p = subprocess.Popen(['klist', '-s'])
    if p.wait():
        kinit(principal, keytab)

def remctl(host, *args, **kws):
    """Perform a remctl and return the output.

    kinits if necessary, and outputs errors to stderr.
    """
    checkKinit(kws.get('principal'), kws.get('keytab'))
    p = subprocess.Popen(['remctl', host]
                         + list(args),
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    v = p.wait()
    if kws.get('err'):
        return p.stdout.read(), p.stderr.read()
    if v:
        print >> sys.stderr, 'Error', v, 'on remctl', args, ':'
        print >> sys.stderr, p.stderr.read()
        raise CodeError('ERROR on remctl')
    return p.stdout.read()
