#!/usr/bin/python

from optparse import OptionParser
from ChrootNonInteractive import Chroot
import os
import sys
import glob
import shutil

# TODO:
# - show held-back packages 
# - if no terminal activity for a extended time, send a '\n' on the
#   terminal (assuming its a stupid maintainer script asking questions)

def login(profile, basedir):
    chroot = Chroot(profile, basedir)
    chroot.bootstrap()
    d = chroot._unpackToTmpdir(chroot.tarball)
    print "logging into: '%s'" % d
    chroot._runInChroot(d, ["/bin/sh"])
    print "Cleaning up"
    if d:
        shutil.rmtree(d)
    
def testUpgrade(profile, basedir):

    # setup log
    os.chdir(basedir)
    fd = os.open(os.path.join(os.path.dirname(profile),"result","out.log"),
                              os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0644)
    os.dup2(fd,1)
    os.dup2(fd,2)
    #fd2 = os.open("/dev/null",os.O_RDONLY)
    #os.dup2(fd2,0)

    # init the chroot
    chroot = Chroot(profile, basedir)
    if not chroot.bootstrap():
        print "FAILED: bootstrap for '%s'" % profile
        return False
    if not chroot.upgrade():
        print "FAILED: upgrade for '%s'" % profile
        return False
    return True

if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("-p", "--profile", dest="profile",
                      help="write report to FILE")
    parser.add_option("-a", "--auto", dest="auto", default=False,
                      action="store_true",
                      help="run all tests in profile/ dir")
    parser.add_option("-l", "--login", dest="login", default=False,
                      action="store_true",
                      help="log into the a profile")
    
    
    (options, args) = parser.parse_args()
    basedir = os.getcwd()
    
    if options.auto:
        for d in glob.glob("./profile/*/DistUpgrade.cfg"):
            #print "Testing: ",d
            testUpgrade(d, basedir)
    elif options.login:
        login(options.profile, basedir)
    else:
        testUpgrade(options.profile, basedir)
    

