#!/usr/bin/env python2.3
# -*- python -*-
from __future__ import division

__version__ = "$Revision: 1.1 $"

from glob import glob
import new
import os
import sys

STDOUT_GLOB="stdout/*"
STDERR_GLOB="stderr/*"
HOSTINFO_DIRNAME="hostinfo"

class DynamicInit(object):
    """
    mix-in class, instantiates on first attribute access

    MUST BE FIRST BASE CLASS USED
    i.e. must appear before the class you want getattribute to use in mro
    """
    def __init__(self, *args, **keywds):
        self.__args = args
        self.__keywds = keywds

    def __getattribute__(self, name):
        _super = super(DynamicInit, self)

        try:
            _super.__init__(*object.__getattribute__(self, "_DynamicInit__args"),
                            **object.__getattribute__(self, "_DynamicInit__keywds"))
            del self.__args
            del self.__keywds
        except AttributeError:
            pass

        return _super.__getattribute__(name)

def dynamic_init(cls):
    new_cls = new.classobj("dynamic_init(%s.%s)" % (cls.__module__, cls.__name__), (DynamicInit, cls), {})
    new_cls.__module__ = __name__
    return new_cls

def filename_number(filename):
    return int(os.path.basename(filename))

def numeric_sort_glob(pattern):
    filenames = [(filename_number(filename), filename)
                 for filename in glob(pattern)]
    filenames.sort()
    return [filename_tuple[1] for filename_tuple in filenames]
    
def cat_stdout(stdout):
    for stdout_filename in numeric_sort_glob(STDOUT_GLOB):
        stdout.write(file(stdout_filename).read())

def cat_stderr(stderr):
    for stderr_filename in numeric_sort_glob(STDERR_GLOB):
        # XXX workaround python bug: print >>filesubclass does not use filesubclass.write()

        for line in file(stderr_filename):
            if not line.startswith("DEBUG") and not line.startswith("INFO"):
                break
        else:
            continue
        
        jobindex = os.path.basename(stderr_filename)
        hostinfo_filename = os.path.join(os.path.dirname(os.path.dirname(stderr_filename)), HOSTINFO_DIRNAME, jobindex)

        stderr.write("### %s\n" % jobindex)

        try:
            hostinfo_text = file(hostinfo_filename).read()
        except IOError:
            hostinfo_text = "### no hostinfo available"
            
        stderr.write(hostinfo_text)
        stderr.write(file(stderr_filename).read())

def arg2output_file(arg):
    if arg == "-":
        return sys.stdout
    else:
        return dynamic_init(file)(os.path.abspath(os.path.expanduser(arg)), "w")

def main():
    last_dir = os.getcwd()

    try:
        try:
            stdout = arg2output_file(sys.argv[2])
        except IndexError:
            stdout = sys.stdout
        try:
            stderr = arg2output_file(sys.argv[3])
        except IndexError:
            stderr = sys.stderr
            
        try:
            os.chdir(os.path.expanduser(sys.argv[1])) # chdir AFTER using abspath on output files 
        except IndexError:
            pass

        cat_stdout(stdout)
        cat_stderr(stderr)
    finally:
        os.chdir(last_dir)

if __name__ == "__main__":
    main()
