#!/usr/bin/python

# This script converts stuff and puts it in the appropriate directories.

import sys, string, os, re, tempfile

def execute( command ):
    print ( command );
    if ( os.system( command ) != 0 ):
        print("ERROR!");
        sys.exit(-1);

mini_counter = 1;

skipping = 0;        

# The basic syntax of input to this tool is:
# "command inputfile outputfile [modifiers]"
# Some of the commands are predefined (macros, if you will) that are project specific.
# "STOP" will halt execution of those lines, and START will start them up again;
# these should only used for debugging

# If outputfile is replaced by TMP, output will be dumped to a TMP file
# The very next TMP on input will use the previous output

if ( not os.environ.has_key('GAMEROOT' ) ):
    print("Be sure to define this variable: GAMEROOT.  It points at the root dir for the game");
    print("You can optionally define ASSETDIR as a subdirectory of GAMEROOT, and that ASSETDIR " )
    print("suffix will be attached to all input files.")
    sys.exit( -1 );

if ( not os.environ.has_key('ROOT' ) ):
    print("I need to know where $ROOT is so I can run rgb2c (among other things).");
    sys.exit(-1 );

if ( not os.environ.has_key('SLI' ) ):
    print("I need to know where $SLI is so I can run sliutil.");
    sys.exit(-1 );


#Set up some variables

DIR = os.environ['GAMEROOT'];

if ( os.environ.has_key('ASSETDIR' )):
    ASSETDIR = DIR + os.environ['ASSETDIR']
else:
    ASSETDIR = DIR

print("ASSETDIR " + ASSETDIR )    
    
ROOT = os.environ['ROOT'];
SLI = os.environ['SLI'];

currentTemp = "ERROR";

def checkForTMPOutput( thing ):
    global currentTemp
    
    if ( thing != "TMP" ): return DIR + thing
    
    currentTemp = tempfile.mktemp();
    
    return currentTemp;

def checkForTMPInput( thing ):
    global currentTemp
    
    if ( thing != "TMP" ): return ASSETDIR + thing

    return currentTemp;
    

def cleanup():

    execute("rm *.i8 *.i8.compressed temp *.rgba");

def sliencType2( line ):

    global mini_counter
    tokens = string.split( line );
    
    inputFile = checkForTMPInput( tokens[ 1 ] );
    outputFile = checkForTMPOutput( tokens[ 2 ] );
    textureName = tokens[ 3 ];

    # sli encode this
    execute( SLI + "/sliutil -c -m " + inputFile + ".converted > " + inputFile + ".compressed " );
    # make a texture out of it with the right name
    execute( "raw2tex.pl " + inputFile + ".compressed " + outputFile + " "+ textureName );
    # get the size of the texture
    execute( "wc " + inputFile + ".compressed > temp ");
    
    f = open ("temp")
    countline = f.readline();
    bob = string.split( countline );
    filesize = bob[2]

    print("Filesize was " + bob[ 2 ] );

    if ( string.atoi( bob[ 2 ] ) == 0 ):
        print("ERROR!  Size was 0!");
        sys.exit(-1);


    if ( string.atoi( bob[ 2 ] ) == 0 ):
        print("ERROR!  Size was 0!");
        sys.exit(-1);

    dealWithSize( tokens[4], filesize, textureName );    

def sliencType1( line ):

    global mini_counter
    tokens = string.split( line );

    inputFile = checkForTMPInput( tokens[ 1 ] );
    outputFile = checkForTMPOutput( tokens[ 2 ] );
    textureName = tokens[ 3 ];

    # now, convert the files from SGI to RGBA
    execute("/usr/X11R6/bin/convert sgi:" + inputFile + " rgba:" + inputFile + ".rgba")
    # from RGBA to i8
    execute( "rgba2i8.pl " + inputFile + ".rgba " + inputFile + ".i8 " );
        
    # sli encode this
    execute( DIR + "../tools/compress/sliutil -c -m " + inputFile + ".i8 > " + inputFile + ".i8.compressed " );
    # make a texture out of it with the right name
    execute( "raw2tex.pl " + inputFile + ".i8.compressed " + outputFile + " "+ textureName );
    # get the size of the texture
    execute( "wc " + inputFile + ".i8.compressed > temp ");
    
    f = open ("temp")
    countline = f.readline();
    bob = string.split( countline );
    filesize = bob[2]

    print("Filesize was " + bob[ 2 ] );

    if ( string.atoi( bob[ 2 ] ) == 0 ):
        print("ERROR!  Size was 0!");
        sys.exit(-1);
    

    dealWithSize( tokens[4], filesize, textureName );


def dealWithSize( token, filesize, textureName ):
    global mini_counter;
    
    # Need to do some work on appending
    if ( token != "N" ):
        if ( token == "PILOT" ):
            charname = textureName[9:]
            execute( "echo \"PILOT_NAME_TEXLIST("+charname+","+filesize+" );\" >> "+ DIR + "/IMAGES/zh/pilot_name_sizes.inc" );
        elif ( token == "GSEL_ICON" ):
            iconname = textureName[9:]
            execute( "echo \"GSEL_ICON_TEXLIST(" + iconname+","+filesize+" );\">> "+ DIR + "GSEL_SIZES.inc" )
        elif ( token == "MINI_SIZE" ):
            iconname = textureName[9:]
            execute( "echo \"MSEL_GRADENAMES_TEXLIST"+str(mini_counter)+"(" + iconname+","+filesize+" );\">> "+ DIR + "MINI_SIZES.inc" )
            mini_counter = mini_counter+1

        elif ( token == "CSEL_CUP" ):
            iconname = textureName[9:]
            execute( "echo \"CSELCUP_TEXLIST(" + iconname+","+filesize+" );\">> "+ DIR + "CSEL_CUP_SIZES.inc" )

        elif ( token == "GSEL_SIZES" ):
            iconname = textureName[9:]
            execute( "echo \"GSEL_LEVELS_TEXLIST(" + iconname+","+filesize+" );\">> "+ DIR + "GSEL_LEVELS_SIZES.inc" )
        elif ( token == "GSEL_SIZES2" ):
            iconname = textureName[9:]
            execute( "echo \"GSEL_LEVELS_TEXLIST2(" + iconname+","+filesize+" );\">> "+ DIR + "GSEL_LEVELS_SIZES.inc" )


        else:
            execute("echo " + filesize + " > " + DIR + token );
    


def rgbType1( line ):

    tokens = string.split( line );

    inputFile = checkForTMPInput( tokens[ 1 ] );
    outputFile = checkForTMPOutput( tokens[ 2 ] );
    textureName = tokens[ 3 ];
    bitCount = tokens[ 4 ];
    colorOrI = tokens[ 5 ];
    invert = tokens[ 6 ];
    if ( invert == "N" ):
        invert = ""
    else:
        invert = "-F"
    
        
    # for reasons known only to itself, you have to convert this from sgi to sgi first
    execute( "/usr/X11R6/bin/convert  "+ inputFile + " sgi:" + inputFile + ".rgb" );                
    execute( ROOT + "/usr/sbin/rgb2c -l 0,0,0 -h 255,255,255 -f " + colorOrI + " " + invert + " -s " + bitCount + " -m " + textureName + " " + inputFile + ".rgb >  " + outputFile);

def rgbType2( line ):

    tokens = string.split( line );

    inputFile = checkForTMPInput( tokens[ 1 ] );
    outputFile = checkForTMPOutput( tokens[ 2 ] );
    args = ""
    for i in range( 3, len( tokens )):
        args = args + tokens[ i ] + " "
    
        
    execute( ROOT + "/usr/sbin/rgb2c " + args +" " + inputFile + " >  " + outputFile);
    


def ascii2Raw( line ):

    tokens = string.split( line );

    inputFile = checkForTMPInput( tokens[ 1 ] );
    outputFile = checkForTMPOutput( tokens[ 2 ] );
    
    execute( "ascii2raw.py < " + inputFile + "  >  " + outputFile);

def stripGFX( line ):

    tokens = string.split( line );
    
    inputFile = checkForTMPInput( tokens[ 0 ] );
    outputFile = checkForTMPOutput( tokens[ 1 ] );

    execute( "grep -v static " + inputFile +" > " + outputFile );
    

def doCommand( line ):

    tokens = string.split( line );
    command = tokens[ 0 ];

    inputFile = checkForTMPInput( tokens[ 1 ] );
    outputFile = checkForTMPOutput( tokens[ 2 ] );

    args = ""
    for i in range( 3, len( tokens )):
        args = args + tokens[ i ] + " "

    execute( command + " " + inputFile + " " + outputFile + " " + args );

def deSli( inputFile, outputFile ):
    inputFile = DIR + inputFile;
    outputFile = DIR + outputFile;
    
    execute( "ascii2raw.py asdf < "+inputFile+" > /tmp/sli; $SLI/sliutil -d /tmp/sli > " + outputFile )

def reSli( inputFile, outputFile, sliFile, symbol ):
    execute("$SLI/sliutil -c -m $GAMEROOT/" + sliFile +" > /tmp/sli.compressed" )
    execute("mergeDotS.py $GAMEROOT/" + inputFile + " $GAMEROOT/" + outputFile + " /tmp/sli.compressed  " + symbol );

foundSomething = 0

def processLine( lines, startWith ):
    global skipping, foundSomething

    skipping = startWith
    skipEverything = 1
    
    if ( startWith != "" ):
        skipEverything = 0

    for line in lines:
        if ( line [ 0 ] == "#" ): continue;

        tokens = string.split( line )        

        if ( len(tokens) == 0 ): continue

        elif ( tokens[ 0 ] == "STOP" ):
            if ( not skipEverything ):
#                print line,
                if ( len( tokens ) > 1  and skipping == 0 and tokens[ 1 ] == startWith ):
                    print "Stopping " + startWith
                    skipping =  tokens[ 1 ]
            else:
                skipping = 1;
            continue;        
        elif ( tokens[ 0 ] == "START" ):
            if ( not skipEverything ): 
#                print line,
#                print "Skipping is " + str( skipping )
                if ( len( tokens ) > 1 and skipping == tokens[ 1 ] ):
                    print "Starting " + startWith
                    foundSomething = 1
                    skipping = 0;
            else:
                skipping = 0;
            continue;
        if ( skipping ): continue
        
        elif ( tokens[ 0 ] == "slienc-type-1" ):
            sliencType1( line );

        elif ( tokens[ 0 ] == "slienc-type-2" ):
            sliencType2( line );

        elif ( tokens[ 0 ] == "rgb2c-type-1" ):
            rgbType1( line );

        elif ( tokens[ 0 ] == "rgb2c-type-2" ):
            rgbType2( line );
            

        elif ( tokens[ 0 ] == "ascii2Raw" ):
            ascii2Raw( line );                        

        elif ( tokens [ 0 ] == "execute" ):
            execute( line[ 8:] );
        elif ( tokens [ 0 ] == "stripGFX" ):
            stripGFX( line[ 8:] );

        elif ( tokens [ 0 ] == "deSli" ):
            deSli( tokens[1], tokens[2]);
        elif ( tokens [ 0 ] == "reSli" ):
            reSli( tokens[1], tokens[2], tokens[3], tokens[4] );
            
            
        else:
            doCommand( line );
        
            

if ( len ( sys.argv ) < 2 ):
    lines = sys.stdin.readlines();
    processLine( lines, "" )
    sys.exit(0);

if ( string.find( sys.argv[1], "CLEANUP" ) != -1 ):
    print "--------cleanup-----------------------"
    cleanup();
    sys.exit(0);
        

f = open( sys.argv[1] )
lines = f.readlines();
f.close();

startWith = ""
if ( len( sys.argv ) > 2 ):
    startWith = sys.argv[2]
    print startWith
processLine( lines, startWith );

if ( startWith != "" ):
    if foundSomething == 0:
        print "CV.PY ERROR: Can't find " + startWith 
        sys.exit( -1 )
    if (len( sys.argv ) > 3):
        f = open( sys.argv[3], "w+")
        f.write("Done!")
        f.close()
        
    




