# Script to generate fortran source code to write compilation information
#
# usage:
# gen_compilation.flags.py file.inc hostname F90 F90FLAGS FPPFLAGS LDFLAGS
#
# output in file "file.inc":
#
# write(ounit, '("HOSTNAME: ",a)') "$(shell hostname)"
# write(ounit, '("F90:      ",a)') "$(F90)"
# write(ounit, '("F90FLAGS: ",a)') "$(F90FLAGS)"
# write(ounit, '("FPPFLAGS: ",a)') "$(FPPFLAGS)"
# write(ounit, '("LDFLAGS:  ",a)') "$(LDFLAGS)"

import sys

if (len(sys.argv) != 7):
    print ("""usage:
    gen_compilation.flags.py file.inc hostname F90 F90FLAGS FPPFLAGS LDFLAGS
""")

outfile = sys.argv[1]
values=[]
values.append(sys.argv[2])
values.append(sys.argv[3])
values.append(sys.argv[4])
values.append(sys.argv[5])
values.append(sys.argv[6])

max_line_length = 132 # hard limit for fortran source code
write_stm_length = 33 # count below
template = "write(ounit, '({:12s},a)') {:s}\n"
cont_stm = '" &\n// "'
tags = ('"HOSTNAME: "', '"F90:      "', '"F90FLAGS: "', '"FPPFLAGS: "', '"LDFLAGS:  "')

with open(outfile,'w') as f:
    for i in range(len(tags)):
        tag = tags[i]
        # add quotes around value
        value = '"' + values[i] + '"'
        # make sure the line length is not too long or split value and add continuation character
        max_length = max_line_length - write_stm_length - len(cont_stm)
        value_lines = []
        while len(value) > max_length:
            value_lines.append(value[0:max_length])
            value = value[max_length:]
            max_length = max_line_length - len(cont_stm)
        value_lines.append(value)
        value = cont_stm.join(value_lines)
        f.write(template.format(tag,value))

    
