#!/usr/bin/env bash

declare -A mapper=(
	["nix"]="nix"
	["sh"]="sh"
)

declare -A edit_file=(
	["nix"]="shell.nix"
)

if [ -z "$1" ]
then
	echo "No argument given. Use --list (-l) to show all options."
	exit 1
fi

if [ "$1" = "-l" ] || [ "$1" = "--list" ]
then
	echo "${!mapper[@]}"
	exit
fi

dest="."
if [ -n "$2" ]
then
	dest="$2"
fi

source="${mapper["$1"]}"
if [ -z "$source" ]
then
	echo "Template not found. Use --list (-l) to show all options."
	exit 1
fi

source="$XDG_CONFIG_HOME/templates/$source"
if [ -f "$source" ]
then
	cp -i "$source" "$dest"
	echo "Template copied."
	source_edit=$dest
elif [ -d "$source" ]
then
	cp -irT "$source" "$dest"
	echo "Template copied."
	source_edit=$dest/${edit_file["$1"]}
else
	echo "Error copying template."
	exit 1
fi

if [ -n "$source_edit" ]
then
	$EDITOR "$source_edit"
fi