#!/usr/bin/env bash

if ! test -d .git; then
    echo "Execute scripts/install-git-hooks in the top-level directory."
    exit 1
fi

ACCOUNT=$(git config -l | grep -w remote.origin.url | sed -e 's/^.*github.com[\/:]\(.*\)\/lab0-c.*/\1/')

CURL=$(which curl)
if [ $? -ne 0 ]; then
    echo "[!] curl not installed." >&2
    exit 1
fi

CURL_RES=$(${CURL} -s \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/${ACCOUNT}/lab0-c/actions/workflows)

TOTAL_COUNT=$(echo ${CURL_RES} | sed -e 's/.*"total_count": \([^,"]*\).*/\1/')
case ${TOTAL_COUNT} in
    *"Not Found"*)
        echo "Check your repository. It should be located at https://github.com/${ACCOUNT}/lab0-c"
        exit 1
esac

if [[ "${ACCOUNT}" != "sysprog21" ]]; then
    REPO_FORKED=$(${CURL} -s \
    -H "Accept: application/vnd.github.v3+json" \
    https://api.github.com/repos/${ACCOUNT}/lab0-c | grep -m 1 fork)
    case ${REPO_FORKED} in
        *true*)
            ;;
        *)
            echo "Your repository MUST be forked from sysprog21/lab0-c"
            exit 1
    esac
fi

if [ ${TOTAL_COUNT} -eq "0" ]; then
    echo "Fatal: GitHub Actions MUST be activated."
    case ${OSTYPE} in
        "linux"*)
            xdg-open https://github.com/${ACCOUNT}/lab0-c/actions > /dev/null 2>&1
            ;;
        "darwin"*)
            open https://github.com/${ACCOUNT}/lab0-c/actions
            ;;
        *)
            echo "Please activate at https://github.com/${ACCOUNT}/lab0-c/actions"
            ;;
    esac
    echo "Check this article: https://docs.github.com/en/actions/managing-workflow-runs/disabling-and-enabling-a-workflow"
    echo "Then, execute 'make' again."
    exit 1
else
    echo "GitHub Actions has been activated"
fi

mkdir -p .git/hooks

ln -sf ../../scripts/pre-commit.hook .git/hooks/pre-commit || exit 1
chmod +x .git/hooks/pre-commit

ln -sf ../../scripts/commit-msg.hook .git/hooks/commit-msg || exit 1
chmod +x .git/hooks/commit-msg

ln -sf ../../scripts/pre-push.hook .git/hooks/pre-push || exit 1
chmod +x .git/hooks/pre-push

touch .git/hooks/applied || exit 1

echo
echo "Git hooks are installed successfully."
