#!/usr/bin/python3

import glob
import re
import subprocess
import sys
from pathlib import Path


def is_excluded(f):
    return (re.match(
        # skip test scripts and the rc.apparmor.slackware initscript
        r"^([.]git/|parser/tst/|tests/|utils/test/|parser/rc[.]apparmor[.]slackware)"
        + "|"
        # skip several files generated during libapparmor build
        + r"^libraries/libapparmor/(compile|config[.]guess|config[.]status|config[.]sub|configure|depcomp|install-sh|libtool|ltmain[.]sh|missing|test-driver|ylwrap|testsuite/test_multi[.]multi)",
        f,
    ) or Path(f).is_dir())


def mimetype(f):
    return subprocess.run(['file', '--brief', '--mime-type', f],
                          stdout=subprocess.PIPE,
                          universal_newlines=True,
                          check=True).stdout.rstrip()


def is_shell_script(f):
    return mimetype(f) == "text/x-shellscript"


shell_scripts = [
    f for f in glob.glob("**/*", recursive=True)
    if not is_excluded(f) and is_shell_script(f)
]

sys.exit(
    subprocess.run(['shellcheck'] + sys.argv[1:] + shell_scripts).returncode)
