#!/usr/bin/python3
# Copyright © 2019 Collabora Ltd.
# SPDX-License-Identifier: BSD-3-Clause
# (See debian/copyright)

import json
import os
import subprocess
import tempfile
from pathlib import Path

if __name__ == '__main__':
    print('1..1')

    with tempfile.TemporaryDirectory() as tmpdir:
        with open(os.path.join(tmpdir, 'Makefile'), 'w') as writer:
            writer.write('''\
hi: hi.c
\t$(CC) -DMAGIC=more_magic -o$@ $<
''')

        with open(os.path.join(tmpdir, 'hi.c'), 'w') as writer:
            writer.write('''\
#include <stdio.h>

int main (void)
{
  puts ("hi, world!");
  return 0;
}
''')

        subprocess.check_call(['bear', '--', 'make'], cwd=tmpdir)

        with open(os.path.join(tmpdir, 'compile_commands.json')) as reader:
            commands = json.load(reader)

        # You get two commands if you're using ccache, so accept any
        # number
        assert len(commands) >= 1, commands

        for command in commands:
            assert '-DMAGIC=more_magic' in command['arguments'], command
            assert command['directory'] == tmpdir, command
            assert (
                (Path(tmpdir) / command['file']).resolve()
                == (Path(tmpdir) / 'hi.c').resolve()
            ), command

    print('ok 1')
