#!/bin/sh
# warn-notangle
# 
# Exit with an error code if there is an error in the notangle process.

function usage() {
   echo "usage: warn-notangle [-LW] [-o output] -- <notangle arguments>" >&2;
   echo " -W treat warnings from notangle as errors" >&2;
   echo " -L add a (use-modules (line-pragma)) header to the file" >&2;
   exit 2;
}
addPrefix=0;
warningsAsErrors=0;
output="";
while getopts hWo:L opt; do
	case $opt in
      L) addPrefix=1;;
	    W) warningsAsErrors=1;;
      h) usage;;
	    o) output=$OPTARG;;
	    *) echo "error: invalid option given." >&2; usage;;
	esac
done
shift $[ OPTIND - 1 ]

function notangle() {
  if [ $addPrefix -eq 1 ]; then
      echo "(use-modules (line-pragma))";
  fi
  /gnu/store/mlcp3sy4hi3n6p9wamh54p4hpmrvyql5-profile/bin/notangle "$@";
}

if [ $# -eq 0 ]; then
    usage;
fi

if [ -z "$output" ]; then
    notangle "$@";
    ec=$?;
else
    notangle "$@" | cpif "$output"; 
    ec=${PIPESTATUS[0]};
fi

if [ $warningsAsErrors -eq 1 ] && [ $ec -ne 0 ]; then
    [ ! -z "$output" ] && rm "$output";
    exit $ec;
else
    exit 0;
fi
