#!/usr/bin/python

import os, sys, time, datetime, pexpect, re

starttime = datetime.datetime.now() 
#                           d s     m h  
tdelta = datetime.timedelta(0,0,0,0,0,6)
#tdelta = datetime.timedelta(0,10,0,0,0,0)
renewtime = starttime + tdelta

#sys.exit(0)

cr, pw =os.pipe()
pr, cw =os.pipe()

pid = os.fork()
if pid:
    #f = open('/tmp/kinit-out-parent.txt','w')
    pgrp = os.getpgrp() 
    lpasswd = sys.stdin.readline()
    passwd=""
    m=re.match(r"PASSWD=(.*)", lpasswd)
    if m != None:
      passwd=m.group(1)
    else:
      #print >>f, "could not read password from stdin"
      sys.exit(1)

    os.close(cr)
    os.close(cw)
    pw = os.fdopen(pw, 'w')
    cr = os.fdopen(pr) # turn r into a file object
    ans=cr.read()
    if(ans=="GETPW"):
      pw.write(passwd)
      pw.close()
    else:
      #print >>f, "child didnt ask for password"
      sys.exit(1)
else:
    #f = open('/tmp/kinit-out-child.txt','w')
    #print >>f, "kinit agent started at", starttime
    pgrp = os.getpgrp() 
    os.close(pw) # use os.close() to close a file descriptor
    os.close(pr) # use os.close() to close a file descriptor
    cw = os.fdopen(cw, 'w')
    cr = os.fdopen(cr) # turn r into a file object
    cw.write("GETPW")
    cw.close()
    passwd = cr.read()
    loop=1
    while loop==1: 
       time.sleep(10)
       if datetime.datetime.now() > renewtime:
          renewtime = datetime.datetime.now() + tdelta
          child = pexpect.spawn ('kinit')
          child.expect ('Password:')
          child.sendline (passwd)
    sys.exit(0)

sys.exit(0)
