#!/usr/bin/env python3

# Copyright 2017 Jussi Pakkanen

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys, os, subprocess

import argparse

parser = argparse.ArgumentParser(description='''Generate cross compilation definition file for the Meson build system.

If you do not specify the --arch argument, Meson assumes that running
plain 'dpkg-architecture' will return correct information for the
host system.
'''
)

parser.add_argument('--arch', default=None,
                    help='The dpkg architecture to generate.')
parser.add_argument('-o', required=True, dest='outfile',
                    help='The output file.')

def run(arch, ofilename):
    if arch is None:
        cmd = ['dpkg-architecture']
    else:
        cmd = ['dpkg-architecture', '-a' + arch]
    output = subprocess.check_output(cmd, universal_newlines=True)
    data = {}
    for line in output.split('\n'):
        line = line.strip()
        if line == '':
            continue
        k, v = line.split('=', 1)
        data[k] = v
    host_arch = data['DEB_HOST_GNU_TYPE']
    host_os = data['DEB_HOST_ARCH_OS']
    host_cpu_family = data['DEB_HOST_GNU_CPU']
    host_cpu = data['DEB_HOST_ARCH'] # Not really correct, should be arm7hlf etc but it is not exposed.
    host_endian = data['DEB_HOST_ARCH_ENDIAN']
    ofile = open(ofilename, 'w')
    ofile.write('[binaries]\n')
    ofile.write("c = '/usr/bin/%s-gcc-6'\n" % host_arch)
    ofile.write("cpp = '/usr/bin/%s-g++-6'\n" % host_arch)
    ofile.write("ar = '/usr/bin/%s-ar'\n" % host_arch)
    ofile.write("strip = '/usr/bin/%s-strip'\n" % host_arch)
    ofile.write("pkgconfig = '/usr/bin/%s-pkg-config'\n" % host_arch)
    ofile.write('\n[properties]\n')
    ofile.write('\n[host_machine]\n')
    ofile.write("system = '%s'\n" % host_os)
    ofile.write("cpu_family = '%s'\n" % host_cpu_family)
    ofile.write("cpu = '%s'\n" % host_cpu)
    ofile.write("endian = '%s'\n" % host_endian)
    ofile.close()

if __name__ == '__main__':
    options = parser.parse_args()
    run(options.arch, options.outfile)
    print('Remember to add the proper --libdir arg to Meson invocation.')
