#!/usr/bin/env python3
import sys
import subprocess
import argparse
from pathlib import Path
from datetime import datetime


def macosx_version_min_updater(s):
    if s.startswith("-mmacosx-version-min="):
        return ""
    else:
        return s


def main():
    parser = argparse.ArgumentParser(description="Helper to set R compilers into your R home config directory")
    parser.add_argument('--cache', type=str, metavar='CACHE_CMD',
                        help="select your cache command. A classical cache command is 'ccache'")
    parser.add_argument('-w', '--write', action="store_true",
                        help="write Makevars in your R config directory [default output is on screen]")
    parser.add_argument('-f', '--overwrite', action="store_true",
                        help="do not save previous configuration in a backup file")
    args = parser.parse_args()

    config = []
    for comp in ['CC', 'CXX', 'CXX11', 'CXX14', 'CXX17', 'FC']:
        try:
            p = subprocess.run(["R", "CMD", "config", comp], capture_output=True)
            cmd = [macosx_version_min_updater(s) for s in p.stdout.decode().split()]
            cmd = list(filter(len, cmd))  # remove empty items
            if args.cache:
                cmd.insert(0, args.cache)
            config.append(f"{comp}=" + " ".join(cmd).strip())
        except Exception as e:
            print(f"An error occurs: {e}", file=sys.stderr)
            print(f"Aborting.", file=sys.stderr)
            sys.exit(1)

    if args.write:
        timestamp = datetime.now()
        rdir = Path.home() / '.R'
        rdir.mkdir(parents=True, exist_ok=True)
        filepath = rdir / 'Makevars'
        if filepath.exists() and not args.overwrite:
            filepathbak = rdir / f"Makevars.bak-{timestamp.strftime('%Y%m%d-%H%m%S')}"
            print(f"'{filepath}' already exists: make a backup in {filepathbak}")
            filepath.rename(filepathbak)
        with filepath.open("w") as f:
            f.write(f"# Generated by Makevars.py for libKriging at {timestamp}\n")
            f.write("\n".join(config) + "\n")
            print(f"Config written in '{filepath}'")
    else:
        print("\n".join(config))


if __name__ == "__main__":
    main()
