#!/bin/sh
# run static code checks like pyflakes and pep8
set -eu

echo "1..4"

cd "${srcdir:-.}"
fail=0

#
# pyflakes
#

if ! which pyflakes >/dev/null 2>&1; then
    echo "ok 1 pyflakes pkg tools # SKIP pyflakes not installed"

elif pyflakes pkg/docker/cockpit-atomic-storage tools/build-debian-copyright >&2; then
    echo "ok 1 pyflakes pkg tools"

else
    echo "not ok pyflakes pkg tools"
    fail=1
fi

# we don't dist bots, so only check it when running in git
[ -d bots ] &&  BOTS=$(grep -l '#!.*python' bots/* 2>/dev/null || true) || BOTS=

# TODO: there are currently a lot of pyflakes errors like
#   'parent' imported but unused
#   'from testlib import *' used; unable to detect undefined names
# Filter these out until these get fixed properly.
if ! which pyflakes >/dev/null 2>&1; then
    echo "ok 2 pyflakes bots test # SKIP pyflakes not installed"

else
    out=$(pyflakes $BOTS test/ test/verify/check-* 2>&1 | grep -Ev "(unable to detect undefined names|defined from star imports|'parent' imported but unused)") || true
    if [ -n "$out" ]; then
        echo "$out" >&2
        echo "not ok 2 pyflakes bots test"
        fail=1
    else
        echo "ok 2 pyflakes bots test"
    fi
fi

#
# wrongly marked translatable strings
#

if out=$(find src/ pkg/ -name '*.js' -o -name '*.jsx' -o -name '*.es6' | xargs grep "_('"); then
    echo 'ERROR: translatable strings must be marked with _("")' >&2
    echo "$out" >&2
    echo "not ok 3 js-translatable-strings"
    fail=1
else
    echo "ok 3 js-translatable-strings"
fi

#
# Unsafe content-security-policy
#
# It's dangerous to have 'unsafe-inline' or 'unsafe-eval' in our
# content-security-policy entries. This is the browser equivalent
# of setenforce 0
#

if grep -E 'content-security-policy.*(\*|unsafe)' pkg/*/*.json*; then
    echo "not ok 4 unsafe-security-policy"
    fail=1
else
    echo "ok 4 unsafe-security-policy"
fi

exit $fail
