#!/usr/bin/env bash

# klevstul

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

src_dir=${DOWNLOADS}
trg_dir=~/Downloads

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

echo "this will empty the directory with all its content:"
tree ${trg_dir}
echo ""
echo "do you want to continue? (y/n)"
read user_input

if [[ ${user_input} != "y" ]]; then
    echo "bye!"
    exit 1
fi

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

    if [[ ${user_input} == "y" ]]; then
        echo "enter the full path to the mounted and synced downloads directory:"
        read -e -p "path: " -i "/home/poq/syncDir/0_downloads" user_input
        src_dir=${user_input}
    else
        echo "set DOWNLOADS, then re-run this script." >&2; exit 1
    fi
fi

trash-put ${trg_dir}
mkdir -p ${trg_dir}

# mount
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}

# set up auto mount
the_file=/etc/fstab
if [ -f "${the_file}" ]; then
    if ! more ${the_file} | grep 'downloads dir'
    then
        echo "" | sudo tee -a ${the_file}
        echo "# auto mount downloads dir" | 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 ""
