#! /bin/bash
#
# tmp.bash
# Copyright (C) 2018 salt <salt@lap-th-e560-0>
#
# Distributed under terms of the MIT license.
#

# Define variables
name="$(basename "$0" .sh)"
tmpdirtemplate="XXXXXX"

# Define functions
log() {
	[ -z "$1" ] && return 1
	# shellcheck disable=1117
	printf "%b: %s\n" \
		"$name" \
		"$1"
}
cleanup() {
	[ -z "$tmpdir" ] && exit 2
	log "Cleaning up \"$tmpdir\""
	rm -rf "$tmpdir"
}

# Handle args
while getopts ":h" opt; do
	case $opt in
		h)
			cat << EOF
Usage: $name [TEMPLATE]
Create a temporary directory, copying the folder [TEMPLATE] from
[XDG_TEMPLATES_DIR|~/Templates]/tmp, if it exists.

  -h			Show this help text

https://gitlab.com/rehashedsalt/bin
EOF
			exit 0
			;;
		*)
			log "Invaild argumenet: -$OPTARG"
			log "See $name -h for help"
			exit 1
			;;
	esac
done

# Validate $1
if [ -n "$1" ]; then
	# Source in XDG dirs, if they exist
	userdirs="${XDG_CONFIG_HOME:-$HOME/.config}/user-dirs.dirs"
	if [ -f "$userdirs" ]; then
		source "$userdirs"
	fi
	unset userdirs
	copydir="${XDG_TEMPLATES_DIR:-$HOME/Templates}/.tmp/$1"
	if ! [ -d "$copydir" ]; then
		log "Could not find template directory \"$copydir\""
		exit 3
	fi
	if ! [ -r "$copydir" ]; then
		log "Cannot read template directory \"$copydir\""
		exit 4
	fi
	log "Using template \"$1\""
	tmpdirtemplate="$1.$tmpdirtemplate"
fi

# Make our directory
tmpdir="$(mktemp -dt "tmp.$tmpdirtemplate")"
[ -z "$tmpdir" ] && exit 2

# Copy in template directory
if [ -n "$1" ] && [ -n "$copydir" ] && [ -n "$tmpdir" ]; then
	cp -r "$copydir"/* "$tmpdir"
	unset copydir
fi

trap "cleanup" EXIT
# Do the do
log "This directory will be removed when this shell exits"
(
cd "$tmpdir" || exit 50
exec "$SHELL"
)