#!/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

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" {} \;

using_unsermake=
if head -n 1 Makefile | grep unsermake >/dev/null; then
    using_unsermake=new
fi
if head -n 1 Makefile | grep automake >/dev/null; then
    using_unsermake=old
fi

top_builddir=`grep '^top_builddir' Makefile | sed -e 's/^.*= *//'`

if test "$using_unsermake" = "new"; then
  # the idea: grab the cxxflags from MakeVars, modify them, and write them down
  # in every Makefile after the line that says .FORWARDS
  toplevelMakefile=$top_builddir/Makefile
  if [ -f $toplevelMakefile ]; then
    # warning this uses sed, so the '?' in the perl regexp above doesn't work here
    cxxflags=`grep ^CXXFLAGS $toplevelMakefile | sed -e 's/[\t ]-O[1-9]\b//g;s/[\t ]-march=\S+\b//g;s/[\t ]-DNDEBUG\b//g;s/[\t ]-DNO_DEBUG\b//g'`
    xpr="s/^CXXFLAGS\s*=.*//; if ( /^\.FORWARDS:/) { "'$_'" .= \"\n$cxxflags -g3\"; }"
    find . $mxdp -name Makefile -exec perl -pi -e "$xpr" {} \;
  else
    echo "ERROR: top_builddir is $top_builddir but $makevars not found"
  fi

elif test "$using_unsermake" = "old"; then
  # the idea: grab the cxxflags from MakeVars, modify them, and write them down
  # in every Makefile after the line that includes MakeVars
  makevars=$top_builddir/MakeVars
  if [ -f $makevars ]; then
    # warning this uses sed, so the '?' in the perl regexp above doesn't work here
    cxxflags=`grep ^CXXFLAGS $makevars | sed -e 's/[\t ]-O[1-9]\b//g;s/[\t ]-march=\S+\b//g;s/[\t ]-DNDEBUG\b//g;s/[\t ]-DNO_DEBUG\b//g'`
    xpr="s/^CXXFLAGS\s*=.*//; if ( /^include .*MakeVars$/) { "'$_'" .= \"\n$cxxflags -g3\"; }"
    find . $mxdp -name Makefile -exec perl -pi -e "$xpr" {} \;
  else
    echo "ERROR: top_builddir is $top_builddir but $makevars not found"
  fi
fi
