#!/bin/bash
#
# Something along the lines of qiv's .qiv-save and .qiv-trash for pqiv.
#
# Copyright (C) 2010-2012 W. Trevor King <wking@drexel.edu>
#
# 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
# (at your option) 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.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#
# usage: cache-file.sh [-l] TAG FILE
#        cache-file.sh [-r] FILE

PREFIX='.cache-'
FILE_DIR=''
CACHE_DIR=''

function check_file()
{
	local FILE="$1"
	if [ ! -e "${FILE}" ]; then
		echo "'${FILE}' doesn't exist" >&2
		exit 1
	fi
	FILE_DIR=$(dirname "${FILE}")
	if [ ! -d "${FILE_DIR}" ]; then
		echo "'${FILE}' not in a directory" >&2
		exit 1
	fi
}

function check_cache()
{
	local TAG="$1"
	local FILE="$2"
	CACHE_DIR="${FILE_DIR}/${PREFIX}${TAG}"

	if [ ! -d "${CACHE_DIR}" ]; then
		if [ -e "${CACHE_DIR}" ]; then
			echo "'${CACHE_DIR}' exists, but is not a directory"
			exit 1
		fi
		mkdir "${CACHE_DIR}"
	fi
}

function move()
{
	local TAG="$1"
	local FILE="$2"
	check_file "${FILE}"
	check_cache "${TAG}" "${FILE}"
	echo "move '${FILE}' to '${CACHE_DIR}'"
	mv "${FILE}" "${CACHE_DIR}"
}

function link()
{
	local TAG="$1"
	local FILE="$2"
	check_file "${FILE}"
	check_cache "${TAG}" "${FILE}"
	echo "hardlink '${FILE}' from '${CACHE_DIR}'"
	cp -l "${FILE}" "${CACHE_DIR}"
}

function restore()
{
	local FILE="$1"
	for CACHED_PATH in $(ls "${PREFIX}"*"/${FILE}"); do
		echo "restore '${FILE}' from '${CACHED_PATH}'"
		mv "${CACHED_PATH}" "${FILE}"
	done
}


if [ "$1" == '-l' ]; then
	link "$2" "$3"
elif [ "$1" == '-r' ]; then
	restore "$2"
else
	move "$1" "$2"
fi
