#!/usr/bin/env bash

# klevstul :: 24.04

this_file_name=`basename "$0"`
echo ":: $this_file_name :: [K] ::"

syncdir_env_var=SYNCDIR_${HOSTNAME}
src_dir=${!syncdir_env_var} # '!' to use the name and not the value
trg_dir=~/syncDir

echo
echo "\$src_dir: ${src_dir}"
echo "\$trg_dir: ${trg_dir}"
echo

if [[ "${src_dir}" == "" ]]; then
    echo "environment variable SYNCDIR_${HOSTNAME} is not set."
    echo ""
    echo "do you want to manually input the sync dir path instead? (y/n)"
    read user_input

    if [[ ${user_input} == "y" ]]; then
        echo "enter the full path to the sync directory:"
        read user_input
        src_dir=${user_input}
    else
        echo "set SYNCDIR, then re-run this script." >&2; exit 1
    fi
fi

if [[ "${src_dir}" == "${trg_dir}" ]]; then
    echo "src == trg. there is nothing to do. bye!" >&2; exit 1
fi

if ! [[ -d ${src_dir} ]]; then
    echo "error: non-existing source directory '${src_dir}'"
    echo "you need to set up sync before you continue!"
    exit 1
fi

if ! [[ -d ${trg_dir} ]]; then
    echo "creating non-existing target directory '${trg_dir}'."
    mkdir -p ${trg_dir}
fi

if mount | grep ${trg_dir} > /dev/null; then
    echo "${trg_dir} is already mounted."
    echo "if you want to unmount this directory, please run:"
    echo "umount ${trg_dir}"
    echo
else
    echo "mounting source '${src_dir}' to target '${trg_dir}'."

    sudo mount -o bind --source ${src_dir} --target ${trg_dir}

    du --human-readable --max-depth=1 ${trg_dir}
fi

# set up auto mount
the_file=/etc/fstab
if [ -f "${the_file}" ]; then
    if ! more ${the_file} | grep 'syncDir'
    then
        echo "" | sudo tee -a ${the_file}
        echo "# auto mount syncDir" | sudo tee -a ${the_file}
        echo "${src_dir}    ${trg_dir}    auto    defaults,nofail,nobootwait,bind 0 2" | sudo tee -a ${the_file}

        echo "> new: auto mount of syncDir added to '${the_file}'":
        cat ${the_file}
    else
        echo "> no change: auto mount of syncDir already existed in '${the_file}'"
    fi
fi

echo ""
