#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

# this script is supposed to apply changes in /sync/{home,root}_external to /sync/{home,root}_external and thus to / resp. ~/
# FIXME!!! WIP
# FIXME!!! syncing root stuff not yet implemented
# FIXME!!! user name/ group name/ home dir hard coded for now...

externalDir=/sync/home_external/
internalDir=/sync/home_internal/
userHome=/home/fabian/
user=fabian
group=fabian
if [[ -z "$1" ]]; then
   echo "Error. No file(s) for import given"
   exit 1
fi

file="$(find $internalDir -name $1)"

# if a file is merely changed, copy its content into the existing target directory
if [[ -e "$file" ]]; then
   echo "copying file content of $1 to $file"
   cat $1 > $file
   exit 0
fi

# if a new file/ dir is created, copy it into the $internalDir retaining the relative path
# after that, copy/ hard link it to the $userHome directory and assign the correct user/ group
# NOTE: one could solve that by having the same user + group on every system
relPath="$(realpath --relative-to=$externalDir $1)" # should also contain the leaf name
echo "new file/dir. relative path: $relPath"
if [[ -f "$1" ]]; then
   install -Dv $1 "$internalDir$relPath"
else
   mkdir -pv "$internalDir$relPath"
fi
cp -lrv "$internalDir$relPath" $userHome
chown -v "$user:$group" "$userHome$relPath"
exit 0
