#!/bin/bash

# based on https://stackoverflow.com/a/9144984

dirs=false
dryrun=false
force=false
ignored=false

svnlist () {
    if $ignored; then
        svn status --no-ignore | grep '^[I?]' | cut -c 9-
    else
        svn status | grep '^[?]' | cut -c 9-
    fi
}

usage () {
    echo "${0##*/} -n|-f [-dx]"
    echo ' -n    Dry run'
    echo ' -f    Real run'
    echo ' -x    Delete ignored files too'
    echo ' -d    Delete directories too'
    echo 'Either -n or -f must be specified'
    exit 2
}

while getopts :dnfx opt; do
    case $opt in
        (n) dryrun=true ;;
        (f) force=true ;;
        (x) ignored=true ;;
        (d) dirs=true ;;
        (*) usage ;;
    esac
done

if (! ($dryrun || $force) ) || ($dryrun && $force); then
    usage
fi

# make sure this script exits with a non-zero return value if the
# current directory is not in a svn working directory
svn info >/dev/null || exit 1

svnlist |
# setting IFS to the empty string ensures that any leading or
# trailing whitespace is not trimmed from the filename
while IFS= read -r f; do
    # tell the user which file is being deleted.  use printf
    # instead of echo because different implementations of echo do
    # different things if the arguments begin with hyphens or
    # contain backslashes; the behavior of printf is consistent
    if [[ -d $f ]] && ! $dirs; then
        continue
    fi
    if $force; then
        printf '%s\n' "Deleting ${f}..."
        rm -rf "${f}" || exit 1
    else
        printf '%s\n' "Would delete ${f}"
    fi
done

