# Pixar's rib exporter has a bug that mistakenly inserts,
#  ##rifcontrol insert begin -rif abind -rifend
# and,
#  Transform [....]
# when it should use,
#  ConcatTransform [....]
# This converter script corrects these mistakes.
# Example of use from a terminal:
#        python ./cleanup_archive.py cube.rib
#
# Malcolm Kesson
# March 5 2019
# Edits: Sept 18 2019
# Removing the following attributes because they cannot be used by Procedurals.
#    Attribute "grouping" "string membership"  ["World"]
#     Attribute "lightfilter" "string subset" [""]
#    Attribute "lighting" "int mute" [0] "string excludesubset" [""]
# Edits: April 17 2020
# Removing: "int indirect" [1] and "int transmission" [1]"
  
import sys
import os
  
def do_strip(ribpath):
    
    if os.path.exists(ribpath) == False:
        print('Error: Cannot find the archive "%s"' % ribpath)
        return
    if os.path.isfile(ribpath) == False:
        print('Error: "%s" is not a regular text file' % ribpath)
        return
    #print('Converting archive rib file\n\t"%s"\n' % ribpath)
    archive_name = os.path.basename(ribpath)[:-4]
  
    temp_name = archive_name + '_temp.rib'
    base = os.path.dirname(ribpath)
    temp_path = os.path.join(base, temp_name)
    
    in_rib = open(ribpath,'r')
    line = in_rib.readline()
    if line:
        temp_rib = open(temp_path, 'w')
    else:
        in_rib.close()
        print('Error: "%s" is an empty file!' % ribpath)
        return
    write_line = True
    while line:
        line = line.strip() + '\n'
        if '"int indirect" [1]' in line:
            line = line.replace('"int indirect" [1]', '')
        if '"int transmission" [1]' in line:
            line = line.replace('"int transmission" [1]', '')
        
        if line.startswith('##rifcontrol insert begin -rif abind -rifend'):
            write_line = False
            
        elif line.startswith('Attribute "grouping"'): # "string membership"  ["World"]'):
            write_line = False
        elif line.startswith('Attribute "lightfilter" "string subset" [""]'):
            write_line = False        
        elif line.startswith('Attribute "lighting" "int mute" [0] "string excludesubset"'):
            write_line = False
  
        # Convert Transform to ConcatTransform
        elif line.startswith('Transform '):
            line = 'Concat' + line
        if write_line: 
            temp_rib.write(line)
        line = in_rib.readline()
        write_line = True
        
    in_rib.close()
    temp_rib.close()
    os.remove(ribpath)
    os.rename(temp_path, ribpath)
    
    print('\nThe archive rib file "%s" has been successfully processed.' % ribpath)
  
if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'Error. Script must be called with the path to a rib archive.'
        print 'For example:'
        print 'python strip_archive.py FULLPATH_TO_ARCHIVE.rib'
    else:
        do_strip(sys.argv[1])