#!/bin/bash

# config/ - configuration files (including shell and profile)
# data/ - resource files used by configured system
# bin/ - scripts used either by configured system or by user

set -e
cd "$(dirname "$(readlink -f -- "$0")")"
umask 002
[[ "$(id -u)" == "0" ]] && echo "ERROR: wrong user" >&1 && exit 1

########## init config #########
if [[ ! -f ~/.config/workspace.conf ]]; then
	mkdir -p ~/.config
	cp config/workspace.conf ~/.config
fi
while read -r line; do
	param="${line::-1}"
	if ! grep -qE "^$param=.+" ~/.config/workspace.conf; then
		echo "ERROR: ~/.config/workspace.conf - missing $param"
		CONFIG_INVALID=1
	fi
done < config/workspace.conf
[[ $CONFIG_INVALID ]] && exit 1
################################

####### file structure #########
USER_DIRS=(
	##### xdg #####
	~/.config		# bkp
	~/.local/bin	# bkp
	~/.local/share	# bkp
	~/.local/state 
	~/.cache
	# app
	~/.local/state/sway
	################
	##### user #####
	~/know		# knowledge base; roam (git)
	~/dev		# projects, version controlled; roam (git)
	~/lfs		# large files
	~/tmp		# temp files, maybe downloads
	################
)
mkdir -p "${USER_DIRS[@]}"
################################

########## scripts #############
cp -rf bin/* ~/.local/bin

LN_EXCLUDE_DIRS=(i3blocks bemenu)

ln_exclude_dirs_cmp=" ${LN_EXCLUDE_DIRS[*]} "
for sdir in bin/*; do
	[ ! -d "$sdir" ] && continue
	sdir="${sdir##*/}"
	[[ $ln_exclude_dirs_cmp == *" $sdir "*  ]] && continue
	find ~/.local/bin -maxdepth 1 -type l -name "$sdir-*" \
		-exec rm {} \;
	#shellcheck disable=SC2016
	find ~/.local/bin/"$sdir" -maxdepth 1 -type f -perm -u+rwx | \
		xargs -0 -d \\n -n 1 sh -c 'ln -s "$1" "/$HOME/.local/bin/$(basename "$(dirname "$1")")-${1##*/}"' sh
done
################################

########### config #############
export IS_COMPAT=0
gomplate --input-dir config \
	--output-map "$HOME/.config/{{ .in | strings.ReplaceAll \".tmpl\" \"\" }}" \
	--exclude-processing "!*.tmpl" \
	--plugin jq=/bin/jq \
	-c theme=config/theme.json \
	-c user="file:///$HOME/.config/workspace.conf?type=application/x-env" \
	--exclude /workspace.conf

ln -sf ~/.config/bash/bashrc ~/.bashrc
ln -sf ~/.config/profile ~/.profile
ln -sf ~/.config/less/lesskey ~/.lesskey
mkdir -p ~/.gnupg && ln -sf ~/.config/gnupg/gpg-agent.conf ~/.gnupg
################################

############# data ############
cp -rf data/* ~/.local/share
###############################

swaymsg reload || true

echo ok