#!/bin/sh
# Modifies the Makefile in the current directory (and optionally its subdirs),
# - to add debug info (-g3)
# - optionally (default) remove optimizations (-O[1-9]?)
# - optionally remove -DNDEBUG and -DNO_DEBUG

if [ -f Makefile.rules ]; then
    echo "Warning, unsermake detected. adddebug can add -g3 but can't remove flags (like -O2 or -DNDEBUG)"
fi

mxdp="-maxdepth 1"
for i in $*; do
  case $i in
    -k) keep=1;;
    -r) mxdp=;;
    -n) ndebug=1;;
    *) echo -e "Usage: adddebug [-k] [-r] [-n]\n  -k: keep optimizations (removed by default)\n  -r: recursive (process all subdirectories)\n  -n: compile without NDEBUG and NO_DEBUG being defined (makes kdDebug calls work)"; exit 1;;
  esac
done

xpr='s/^((C|CXX|LD)FLAGS[ \t]*=.*)$/\1 -g3/'
if test -z $keep; then
  xpr="$xpr;"'s/[\t ]-O[1-9]?\b//g'
  xpr="$xpr;"'s/[\t ]-march=\S+\b//g'
fi
if test -z $ndebug; then
  xpr="$xpr;"'s/[\t ]-DNDEBUG\b//g'
  xpr="$xpr;"'s/[\t ]-DNO_DEBUG\b//g'
fi
find . $mxdp -name Makefile -exec perl -pi -e "$xpr" {} \;

# unsermake support
if [ -f Makefile.rules ]; then
  xpr='s/(\$\(CXXFLAGS\) )/\1 -g3 /'
  find . $mxdp -name Makefile.rules -exec perl -pi -e "$xpr" {} \;
fi
