#!/usr/bin/env bash
# hide -- move no longer useful files to the attic

. lib.bash || exit

usage() {
	echo "Usage: $progname [-c] [-d <dir>] [-y <year>] <files>..."
	echo ""
	echo "Put away old files to ~/Attic/Misc/<year>."
	echo ""
	echo_opt "-c"		"Copy instead of moving"
	echo_opt "-d <dir>"	"Put files in a subdirectory"
	echo_opt "-y <year>"	"Use specified year instead of modification time"
}

dir="$HOME/Attic/Misc"

if [[ ! -d $dir ]]; then
	dir="/net/ember/home/grawity/Attic/Misc"
	if [[ ! -d $dir ]]; then
		vdie "misc directory not found and not accessible via NFS"
	fi
	vmsg "using NFS location ($dir)"
fi

arg_subdir=
arg_year=
arg_copy=0

while getopts ":cd:y:" OPT; do
	case $OPT in
	c) arg_copy=1;;
	d) arg_subdir=$OPTARG;;
	y) arg_year=$OPTARG;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

if (( ! $# )); then
	vdie "no files specified"
fi

if [[ $arg_year == @(now|today) ]]; then
	arg_year=$(date +%Y)
fi

for arg; do
	if [[ ! -e $arg ]]; then
		vmsg "not found: \"$arg\"" >&2
		let ++errors
		continue
	elif [[ -L $arg || ! ( -f $arg || -d $arg ) ]]; then
		vmsg "not a regular file: \"$arg\"" >&2
		let ++errors
		continue
	fi

	src=$(readlink -f "$arg")
	# separate name/extension for adding "-counter" if needed
	ext=""
	base=$(basename "$arg")
	if [[ $base == *.* ]]; then
		ext=${base##*.}
		base=${base%.*}
	fi

	if [[ $arg_year ]]; then
		dstdir=$dir/$arg_year
	else
		dstdir=$dir/$(date +%Y -d "@$(stat -c %Y "$arg")")
	fi

	if [[ $arg_subdir ]]; then
		dstdir=$dstdir/$arg_subdir
	fi

	mkdir -p "$dstdir"

	count=1
	dst="$dstdir/$base${ext:+.}$ext"
	while [[ -e $dst ]]; do
		let ++count
		dst="$dstdir/$base-$count${ext:+.}$ext"
	done

	if (( arg_copy )); then
		vmsg "copying \"$src\" to \"${dst#$HOME/}\""
		cp -b -p "$src" "$dst"
	else
		vmsg "moving \"$src\" to \"${dst#$HOME/}\""
		mv -b "$src" "$dst"
	fi || let ++errors
done

(( ! errors ))
