#!/usr/bin/env python

import sys, os, subprocess, getopt

def usage():
    print("""\n\

mklib is a small wrapper for ar to work around limited command line
length in some os'es. The user provides a file containing a list of
object files, mklib assembles the library in batches of N .o files
(see below)

usage:\n\
\n\
    mklib [-v -h -n N] LIB OBJLIST\n\
\n\
    -h       this message
    -v       be verbose
    -d       debug output
    -a FLAG  use FLAG for ar to add files to a library\n\
             example; for 64bit AIX use
                ls -1 *.o > OBJS
                mklib -a "-X64 -r" libtest.a OBJS\n\
    N        the number of files in each batch for ar\n\
    LIB      the name of the final library\n\
    OBJLIST  file with list of object files\n\
""")

maxobjs = 100
verbose = 0
debug=0

# linux ar is the default.
ar_add_flag="r"
if os.uname()[0]=='AIX':
    ar_add_flag="-X64 -r"


if len(sys.argv)<2:
    print("too few arguments")
    usage()
    sys.exit(2)

try:
    opts, args = getopt.getopt(sys.argv[1:], "n:vha:d")
    if opts!=[]:
        for opt, value in opts:
            if opt in ("-h"):
                usage()
                sys.exit(2)
            if opt in ("-n"):
                maxobjs = int(value)
            if opt in ("-a"):
                ar_add_flag = value
            if opt in ("-v"):
                verbose=1
            if opt in ("-d"):
                debug=1

except getopt.GetoptError:
    print("Unknown options:", sys.argv[1:])
    usage()
    sys.exit(2)


if debug:
    print("ar add flag set to:",ar_add_flag)
    print("maxobjs:",maxobjs)

libname = sys.argv[-2]

print('mklib: Will try to create the library "'+libname+'" out of all files in "' + sys.argv[-1] + '"')

if os.access(sys.argv[-1], os.F_OK):
    f = open(sys.argv[-1], 'r')
else:
    print("could not open file ",sys.argv[-1])
    sys.exit(1)

if os.access(libname, os.F_OK and os.W_OK):
    os.remove(libname)

objs = ""
numobjs = 0

for line in f:
    if line.strip()=="":
        continue
    if line.strip()[0]=="#":
        continue
    if line.find("=")>-1:
        continue

    filename = line.split()[0]

    if os.access(filename, os.F_OK and os.W_OK):
        numobjs += 1
        objs += filename + " "

    if debug: print("%3.3i"%numobjs, line.split())

    if numobjs >= int(maxobjs):
        command = "ar " + ar_add_flag + " " + libname + " " +objs
        if verbose or debug: print(command)
        stat, out = subprocess.getstatusoutput(command)
        if stat!=0 or debug:
            print("command:",command)
            if not debug: print("ERROR:  ar failed with output:")
            print("out:",out)
            if not debug: break
        numobjs=0
        objs=""

if objs!="":
    command = "ar " + ar_add_flag + " " + libname + " " +objs
    if verbose or debug: print("Finally;", command)
    stat, out = subprocess.getstatusoutput(command)
    if debug: print(out)
    if stat!=0:
        print(command)
        print("ERROR:  ar failed with output:")
        print(out)
