#!/usr/bin/bash -eu

if [[ "$#" -lt 1 ]]; then
	echo "Usage: linkify FILES..."
	exit 1
fi

home=$HOME
script_dir=`dirname $(realpath "$0")`
script_home="$script_dir/home"

fof=0
links=0
files=0

for file in "$@"
do
	if [[ -h "$file" ]]; then
		((links++))
	elif [[ -d "$file" ]]; then
		echo "$file is directory, skipping"
	elif [[ -f "$file" ]]; then
		real_path_file="$(realpath "$file")"
		check_home="$(echo "$real_path_file" | cut -d'/' -f-3)"
	
		if [[ "$home" = "$check_home" ]]; then
			relative_path="$(echo "$real_path_file" | cut -d'/' -f4-)"
			desired_path="$script_home/$relative_path"
			mkdir -p "$(dirname "$desired_path")"
			mv "$file" "$desired_path"

			if [[ "$file" == *".fof" ]]; then
				cp "$desired_path" "${file::-4}"
				((fof++))
			else
				ln -s "$desired_path" "$file"
				((files++))
			fi
		else
			echo "$file is not under $home, skipping"
		fi
	else
		echo "$file does not exist"		
	fi
done

echo "##### linkify result #####"
echo "$links link(s) skipped, $files file(s) linkified, $fof fire and forget config(s) renamed and saved"