#!/bin/bash
DRY_RUN=false
DISPLAY_HELP=false
DISPLAY_VERSION=false
DIRECTORY=""
MAGIC_LINE="// THIS IS A GENERATED FILE - DO NOT EDIT"
ME=`basename "$0"`

#Define standard functions
function printUsage {
    echo "usage: $ME directory [OPTIONS]"
    echo
    echo "Cleans all cpp variants from a directory based on the wscript of that directory."
    echo
    echo "WARNING: 'variant' cpp files are determined based on whether they have the string:"
    echo "$MAGIC_LINE"
    echo "as the first line of the file. If you have a file starting with the same line, it"
    echo "will be deleted without further notification. Run with -d first to make sure you"
    echo "don't delete anything important."
    echo 
    echo "positional arguments:"
    echo "  directory      : The directory to be cleaned"
    echo
    echo "optional arguments:"
    echo "  -h, --help     : Display this help message and exit"
    echo "  -v, --version  : Display version information and exit"
    echo "  -d, --dryrun   : Print all files to be deleted, but don't delete them"
}
function printVersion {
    echo "Clean variants by Joost Huizinga, version 1.0."
}
function printError {
    echo "Error: $1"; printUsage; exit 1
}
function printAndRun {
    echo "$1"
    if [[ "${DRY_RUN}" == false ]]; then $1; fi
}

#Read commandline arguments
while [[ $# > 0 ]]; do
    case "${1}" in
      -h | --help ) DISPLAY_HELP=true;;
      -v | --version ) DISPLAY_VERSION=true;;
      -d | --dryrun ) DRY_RUN=true;;
      -* ) printError "Unknown option ${1}";;
      * ) if [[ -z "${DIRECTORY}" ]]; then
              DIRECTORY="$1"
          else
              printError "To many positional arguments provided:${1}"
          fi
    esac
    shift
done

#Process options
if [[ "$DISPLAY_HELP" == true ]]; then printUsage; exit 0; fi
if [[ "$DISPLAY_VERSION" == true ]]; then printVersion; exit 0; fi
if [[ ! -d "$DIRECTORY" ]]; then printError "$DIRECTORY is not a directory."; fi

#Find all files that have the MAGIC_LINE and delete them
find "$DIRECTORY" -name "*.cpp" -print0 | while read -d $'\0' FILE
do
    FIRST_LINE=`head -n 1 $FILE`
    if [[ $FIRST_LINE == $MAGIC_LINE ]]; then
        printAndRun "rm $FILE"
    fi
done
