#!/usr/bin/python

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

from campus_factory.util.DaemonWrangler import DaemonWrangler
from campus_factory.ClusterStatus import CondorConfig
from optparse import OptionParser
import os, sys, pwd
import logging



def add_options(parser):

    parser.add_option("-o", "--outputtar", dest="outputtar", 
                        help="Where to store the output glidein tar", 
                        action="store", default="")




def parse_options():
    usage = "usage: %prog [options] clusterhost input_condor"
    parser = OptionParser(usage)
    add_options(parser)
    (returned_options, returned_args) = parser.parse_args()
    return returned_options, returned_args





def main():
    (options, args) = parse_options()
    if len(args) is not 2:
        print "Error parsing options, exactly 2 arguments needed"
        print str(args)
        sys.exit(1)
     
    logging.getLogger().setLevel(logging.ERROR)
    
    clusterhost = args[0] 
    condor_dir = args[1]
    
    condor_config = CondorConfig()
    IDS = condor_config.get("CONDOR_IDS")
    if IDS != "":
        (factory_uid, factory_gid) = IDS.split(".")
        if int(factory_uid) != os.getuid():
            print "factory_uid = %i, getuid = %i" % ( int(factory_uid), os.getuid() )
            print "glidein_creation is not running as the factory user."
            print "Not packaging glideins for %s" % clusterhost
            sys.exit(0)
    
    dw = DaemonWrangler(base_condor_dir = condor_dir, dumb_package = True)
    
    # Get the condor localdir
    if options.outputtar is not "":
        finalLocation = options.outputtar
    else:
        local_dir = condor_config.get("LOCAL_DIR")
        finalLocation = os.path.join(local_dir, "factory_glideins", clusterhost, "glideinExec.tar.gz")
    
    # Try making the directory
    if not os.path.exists(os.path.dirname(finalLocation)):
        os.makedirs(os.path.dirname(finalLocation))
        
    dw.Package(name=finalLocation)
    



if __name__ == "__main__":
    main()



