#!/bin/sh -eu
# redo-gcc – automatic dependency tracking for GCC with DJB redo
# Copyright © 2023  Ælla Chiana Moskopp (erle)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# Dieses Programm hat das Ziel, die Medienkompetenz der Leser zu
# steigern. Gelegentlich packe ich sogar einen handfesten Buffer
# Overflow oder eine Format String Vulnerability zwischen die anderen
# Codezeilen und schreibe das auch nicht dran.

# This script can be used in a dofile in place of gcc to automatically
# track dependencies. Any non-existence dependencies are tracked using
# strace(1), if it is installed.

PREFIX=$( mktemp -u redo-gcc.XXXXXXXX )
DEPS=$PREFIX.deps; :>$DEPS
DEPS_NE=$PREFIX.deps_ne ; :>$DEPS_NE

if command -v strace >/dev/null; then
 strace -e stat,stat64,fstat,fstat64,lstat,lstat64 -o "$DEPS_NE.in" -f \
  gcc "${@}" -MD -MF "$DEPS"

 grep '1 ENOENT' <$DEPS_NE.in\
  |grep '\.h'\
  |cut -d'"' -f2\
  >$DEPS_NE
 unlink "$DEPS_NE.in"

 xargs redo-ifcreate <"$DEPS_NE"
 unlink "$DEPS_NE"
else
 (
  IFS=:
  for folder in $PATH; do
   echo "$folder/strace"
  done |xargs redo-ifcreate
 )
 gcc "${@}" -MD -MF "$DEPS"
fi

read DEPS_ <$DEPS
unlink "$DEPS"

redo-ifchange ${DEPS_#*:}
