#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 Matthias Klumpp <mak@debian.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
#
# The same code is also part of the Meson build system and available under
# the terms of the Apache License, Version 2.0

import os
import sys


from typing import List, Dict


TRANSLATE_TABLE: Dict[str, str] = {
    # We currently can't auto-handle LDC LTO in the Debian build system.
    # "-ffat-lto-objects": "-ffat-lto-objects",
    # "-flto=auto": "-flto=full",
    "-fno-omit-frame-pointer": "--frame-pointer=non-leaf",
    "-fcf-protection": "-fcf-protection=full",
    "-m32": "-m32",
    "-m64": "-m64",
    "-mhard-float": "--float-abi=hard",
    "-msoft-float": "--float-abi=soft",
    "-fPIC": "--relocation-model=pic",
    "-g": "-g",
    "-O0": "-O0",
    "-O1": "-O1",
    "-O2": "-O2",
    "-O3": "-O3",
}


def translate_args_to_nongnu(args: List[str], ignore_unknown=False):
    dcargs = []
    # Translate common arguments to flags the LDC/DMD compilers
    # can understand.
    # The flags might have been added by pkg-config files,
    # and are therefore out of the user's control.
    for arg in args:
        if arg in TRANSLATE_TABLE:
            dcargs.append(TRANSLATE_TABLE[arg])
            continue
        if arg == "-pthread":
            continue
        if arg.startswith("-Wl,"):
            linkargs = arg[arg.index(",") + 1:].split(",")
            for la in linkargs:
                dcargs.append("-L" + la.strip())
            continue
        elif arg.startswith("-l"):
            # translate library link flag
            dcargs.append("-L" + arg)
            continue
        elif arg.startswith("-L/") or arg.startswith("-L./"):
            # we need to handle cases where -L is set by e.g. a pkg-config
            # setting to select a linker search path. We can however not
            # unconditionally prefix '-L' with '-L' because the user might
            # have set this flag too to do what it is intended to for this
            # compiler (pass flag through to the linker)
            # Hence, we guess here whether the flag was intended to pass
            # a linker search path.
            dcargs.append("-L" + arg)
            continue
        if arg.startswith("-march="):
            # LDC's -march selects the target architecture, not the ISA
            # level; x86-64 psABI levels are valid LLVM -mcpu values.
            value = arg[len("-march="):]
            if value.startswith("x86-64"):
                dcargs.append("-mcpu=" + value)
            continue
        if not ignore_unknown:
            dcargs.append(arg)

    return dcargs


def main():
    if len(sys.argv) <= 1:
        print()
        return

    gcc_flags = sys.argv[1:]
    if not gcc_flags:
        ldflags = os.environ.get("LDFLAGS")
        gcc_flags = ldflags.split() if ldflags else []
    if not gcc_flags:
        print()
        return
    ignore_unknown = gcc_flags[0] == "--dh-dlang-ignore-unknown-options"

    print(" ".join(translate_args_to_nongnu(gcc_flags, ignore_unknown)))


if __name__ == "__main__":
    main()
