#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# File: intercept
# Author: Lorenz Stechauner <e12119052@student.tuwien.ac.at>
#         Lorenz Stechauner <lorenz.stechauner@necronda.net>

import argparse
import subprocess
import os
import sys


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('-F', '--functions')
    parser.add_argument('-s', '--sparse', action='store_true')
    libs = parser.add_mutually_exclusive_group()
    libs.add_argument('-o', '--only-own', action='store_true')
    libs.add_argument('-L', '--libraries')
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument('-l', '--log')
    mode.add_argument('-i', '--intercept')
    args, extra = parser.parse_known_args()
    if len(extra) > 0 and extra[0] == '--':
        extra.pop(0)
    if len(extra) == 0:
        parser.error("command expected after arguments or '--'")

    if args.intercept:
        intercept = args.intercept
    elif args.log:
        intercept = 'file:' + args.log
    else:
        intercept = 'stderr'
    subprocess.run(extra, stdin=sys.stdin, env={
        'LD_PRELOAD': os.getcwd() + '/intercept.so',
        'INTERCEPT': intercept,
        'INTERCEPT_VERBOSE': '0' if args.sparse else '1',
        'INTERCEPT_FUNCTIONS': args.functions or '*',
        'INTERCEPT_LIBRARIES': '*,-/lib*,-/usr/lib*' if
            args.only_own else args.libraries or '*',
    })


if __name__ == '__main__':
    main()
