#!/bin/sh

set -eu

newdockerignore=$(mktemp)
newackrc=$(mktemp)
newctags=$(mktemp)
trap "rm -rf $newdockerignore $newackrc $newctags" INT TERM EXIT

sed -e '
s/SYNC WITH .dockerignore/SYNC WITH .gitignore/
/\/squad\/frontend\/static\// d
s#^[^/#]#**/&#
s#^/##
' .gitignore > "$newdockerignore"

sed -e '
s/SYNC WITH .dockerignore/SYNC WITH .gitignore/
/\(\/static\|\/squad\/frontend\/static\)/ !d
s#\/\(.*\)#--ignore-dir=\1#
' .gitignore > "$newackrc"

sed -e '
s/SYNC WITH .dockerignore/SYNC WITH .gitignore/
/\(\/static\|\/node_modules\|\/doc\|\/squad\/frontend\/static\)/ !d
s#\/\(.*\)#--exclude=\1#
' .gitignore > "$newctags"
cat >> "$newctags" <<EOF
--exclude=test/*
--exclude=scripts/*
--recurse
EOF

update=no
if [ "${1:-}" = '--update' ]; then
    update=yes
fi

check() {
    new="$1"
    old="$2"
    if [ "${update}" = 'yes' ]; then
        cat "$new" > "$old"
    else
        if ! diff -u "$old" "$new"; then
            echo
            echo "# $old is out of date! Re-run this script as \`$0 --update\`"
            exit 1
        fi
    fi
}

check "$newdockerignore" .dockerignore
check "$newackrc" .ackrc
check "$newctags" .ctags
