#!/bin/sh

VERSION=0.1.0

target="$(cd .. && pwd)"
stowdir="$(pwd)"
no=
verbose=

version () {
    stow_version="$(stow -V 2>/dev/null)"

    cat <<EOF
unstow version $VERSION / ${stow_version-stow(1) not found}
EOF
}

usage () {
    version
    cat <<EOF
Usage: $0 [OPTION ...] PACKAGE ...
  -n              Do not actually make changes
  -d DIR          Set stow dir to DIR (default is current dir)
  -t DIR          Set target to DIR (default is parent of stow dir)
  -v              Be verbose
  -V              Show Unstow and Stow version numbers
  -h              Show this help
EOF
    exit 64
}

while getopts fnvt:d: OPTION; do
    case "$OPTION" in
        t)
            target="$(cd "$OPTARG" && pwd)"
            ;;
        d)
            stowdir="$(cd "$OPTARG" && pwd)"
            ;;
        f)
            force=t
            ;;
        n)
            no=t
            ;;
        v)
            verbose=t
            ;;
        h)
            usage
            ;;
        V)
            version
            exit 0
            ;;
        *)
            usage
            ;;
    esac
done

shift $(($OPTIND - 1))

if [ $# -eq 0 ]; then
    echo "$0: No packages named"
    usage
fi

for package; do
    (cd "$stowdir/$package" && find .) | while read file; do
        path="$target/${file#./}"

        if [ ! -e "$path" -a ! -L "$path" ]; then
            continue
        fi

        if [ -n "$force" -o -L "$path" ]; then
            if [ -n "$no" -o -n "$verbose" ]; then
                echo "removing \`$path'"
            fi

            if [ -z "$no" ]; then
                rm -- "$path"
            fi
        else
            echo "leaving \`$path'"
        fi
    done
done
