#!/bin/bash

# findtf - find temporary files
# Copyright © 2000-2009 by Pádraig Brady <P@draigBrady.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details,
# which is available at www.gnu.org

script_dir=$(dirname "$0")              #directory of this script
script_dir=$(readlink -f "$script_dir") #Make sure absolute path

. "$script_dir"/supprt/fslver

Usage() {
    ProgName=$(basename "$0")
    echo "find Temporary Files.
Usage: $ProgName [-c] [--age=days] [[-r] [-f] paths(s) ...]

If -c specified then a more thorough search is done for
(and only for) core files, and more information is printed about them.

If --age=days specified then the temporary files must be over that
number of \"days\" old before being reported.
For e.g. findtf -c --age=4 only reports core files over 4 days old.

If no path(s) specified then the current directory is assumed."
    exit
}

MIN_AGE=0 #days

for arg
do
    case "$arg" in
    -h|--help|-help)
        Usage ;;
    -v|--version)
        Version ;;
    --age=*)
        days=$(echo $arg | cut -b7-)
        [ "$days" ] && MIN_AGE=$days ;;
    -c)
        core_mode="yes" ;;
    *)
        argsToPassOn="$argsToPassOn $(shell_quote "$arg")" ;;
    esac
done

if [ "$MIN_AGE" != "0" ]; then
    FIND_AGE="-mtime +$MIN_AGE"
fi

if [ "$force_full" = "yes" ]; then
    . "$script_dir"/supprt/getfpf -f "$argsToPassOn"
else
    . "$script_dir"/supprt/getfpf "$argsToPassOn"
fi

if [ "$core_mode" = "yes" ]; then
    find "$@" -type f -name "*core*" $FIND_AGE ! -name "*$LF*" -printf "%p\n" |
    grep -E "/core$|\.core$|/core\.[0-9]+$" |
    xargs -r file |
    grep -F "core file " |
    if [ -p /proc/self/fd/1 ]; then
        cut -f1 -d: #only leave filename
    else
        cat
    fi
    exit
fi

# .v are rcs files
# .swp are vi backup files are shouldn't be removed really?
# Hrm well vi doesn't delete after restore?
# dead.letter generated by pine and sendmail I think
# #*# & *~ are EMACS
# *.pure is purify remains

tmpFiles="core dead.letter '*~' ',*' '*.v' tmp junk '\#*' \
'.emacs_[0-9]*' '*.[Bb][Aa][Kk]' '*.swp' '*.pure'"

# build "find" command line
Names=
for name in $tmpFiles
do
    [ -n "$Names" ] && Names="$Names -o "
    Names="${Names}-name $name"
done
Names="\( $Names \)"

eval find '"$@"' -type f $Names $FIND_AGE -printf "$FPF'\0'" |
sort -zu | #merge files (indirectly) specified multiple times
tr '\0' '\n'
