#!/usr/bin/env python3

import os

import common
from shell_helpers import LF

class Main(common.LkmcCliFunction):
    def __init__(self):
        super().__init__(
            defaults = {
                'show_time': False,
            },
            description='''\
Manually run a ToolChain tool like gcc, readelf or objdump.
https://cirosantilli.com/linux-kernel-module-cheat#run-toolchain
''',
        )
        self.add_argument(
            '--print-tool',
            default=False,
            help='''
Just output print tool path to stdout but don't actually run it.
Suitable for programmatic consumption by other shell programs.
''',
        )
        self.add_argument('tool', help='Which tool to run.')
        self.add_argument(
            'extra_args',
            default=[],
            help='Extra arguments for the tool.',
            metavar='extra-args',
            nargs='*'
        )

    def timed_main(self):
        tool = self.get_toolchain_tool(self.env['tool'])
        if self.env['print_tool']:
            print(tool)
            return 0
        else:
            return self.sh.run_cmd(
                [tool, LF]
                + self.sh.add_newlines(self.env['extra_args']),
                cmd_file=os.path.join(self.env['run_dir'], 'run-toolchain.sh'),
            )

if __name__ == '__main__':
    Main().cli()
