#!/usr/bin/bash -eu

echo ===============================
echo Starting deploy.

deploy_path="$HOME"
dummy_home="./home"

cd "$(dirname "$0")"
dummy_home_abs=$(pwd)/home
additional_list=""
while read line; do
	folder_path=$(dirname "$line")
	file=$(basename "$line")
	folder_path=${folder_path:6}
	if [[ "$folder_path" != "" ]]; then
		mkdir -p "$deploy_path""$folder_path"
	fi

	config_path="$dummy_home_abs""$folder_path"/"$file"
	desired_path="$deploy_path""$folder_path"/"$file"
	if [[ "$file" == *".fof" ]]; then
		desired_path=${desired_path::-4}
	fi

	if [[ "$folder_path" == *"additional.d"* ]]; then
		if [[ "$additional_list" != *"$folder_path"* ]]; then
			additional_list+='\n\n'"$folder_path"
		fi

		already_deployed="-"
		if [[ -L "$desired_path" ]]; then
			already_deployed="+"
		fi

		additional_list+='\n'"$already_deployed""$file"
	else
		if [[ "$file" != *".fof" && ( -L "$desired_path" || (  ! -f "$desired_path" && ! -d "$desired_path" ) ) ]]; then
			ln -sf "$config_path" "$desired_path"
		else
			if [[ (  -f "$desired_path".deploy_backup || -d "$desired_path".deploy_backup ) ]]; then
				rm -r "$desired_path".deploy_backup
			fi
			
			if [[ (  -f "$desired_path" || -d "$desired_path" ) ]]; then
				mv -T "$desired_path" "$desired_path".deploy_backup
			fi

			if [[ "$file" == *".fof" ]]; then
				echo Deploying fire and forget config: "$desired_path"
				cp "$config_path" "$desired_path"
			else
				echo Path exists, moved to filename.deploy_backup: "$desired_path"
				ln -sf "$config_path" "$desired_path"
			fi
		fi
	fi
done < <(find "$dummy_home" -type f)

echo
echo ===============================
echo Deploy finished.
echo
echo ===============================
echo Additional configs to consider:
additional_list=${additional_list:4}
echo -e "$additional_list"