#!/bin/bash

_usage() {
    echo "`basename $0` [ -f ] [ DIRS... ]"
    echo "`basename $0` [ -h | --help ]"
}

if [ "$1" = -h -o "$1" = "--help" ]; then
   _usage
   exit 1
fi

if [ "$1" = "-f" ];then
   FORCE=yes
   shift
else
   FORCE=no
fi

if [ $# = 0 ]; then
  DIRS=`pwd`
else
  DIRS="$*"
fi

if [ $FORCE != "yes" ]; then
  echo "To clean we suggest to:"
  echo "DELETE:"
  (
  find $DIRS -type f \( -path '*/*.ana/*' -o -path '*/*.dir/*' \) -o \( -name '*.deploy.js' -o -name '*.use.js' \) -o -name '*~' 2>/dev/null
  ) | sort -u
  echo "... and all (resulting) empty dirs"
  echo "KEEP:"
  (
  find $DIRS -type f \! \( \( -path '*/*.ana/*' -o -path '*/*.dir/*' \) -o \( -name '*.deploy.js' -o -name '*.use.js' \) -o -name '*~' \) 2>/dev/null
  ) | sort -u
  echo -n "Really clean [y|N]: "
  read IN
fi

if [ $FORCE = "yes" -o "$IN" = "y" -o "$IN" = "Y" -o "$IN" = "yes" ]; then
  find $DIRS \( -type f \( -path '*/*.ana/*' -o -path '*/*.dir/*' \) -o \( -name '*.deploy.js' -o -name '*.use.js' \) -o -name '*~' \) -exec rm -vf {} \; 2>/dev/null
  find $DIRS -type d -empty -exec rmdir -v {} \; 2>/dev/null
  find $DIRS -type d -empty -exec rmdir -v {} \; 2>/dev/null
else
  echo "quit. done nothing."
fi
