#!/bin/bash

dir_orig=$(pwd)
if [[ -d "$HOME/dotfiles/config/setup/rclone_remote" ]]; then
    echo "Path $HOME/dotfiles/config/setup/rclone_remote does not exist. Aborting"
    exit 1
fi

rclone_remote=$(cat "$HOME/dotfiles/config/setup/rclone_remote")

## Parse command-line arguments
#while getopts "m:-:" opt; do
#  case $opt in
#    m)
#      commit_message="$OPTARG"
#      ;;
#    -)
#      case "${OPTARG}" in
#        message=*)
#          commit_message="${OPTARG#*=}"
#          ;;
#        *)
#          echo "Invalid option: --${OPTARG}" >&2
#          exit 1
#          ;;
#      esac
#      ;;
#    \?)
#      echo "Invalid option: -$OPTARG" >&2
#      exit 1
#      ;;
#  esac
#done

# Set default commit message if not specified
if [ -z "$commit_message" ]; then
  commit_message="a new version"
fi

echo ""
echo "=============================== Committing Local Changes ==================================="
cd ~/dotfiles || exit 1
git status
git add .
git commit -am $commit_message


echo ""
echo ""
echo "=============================== Downloading Remote Repo ===================================="
mkdir -p ~/.machineconfig/sync_dotfiles
rm -rf ~/.machineconfig/sync_dotfiles/* > /dev/null 2>&1
rm -rf ~/.machineconfig/sync_dotfiles > /dev/null 2>&1
cloud_rx "$rclone_remote" myhome/generic_os/dotfiles -zew -l ~/.machineconfig/sync_dotfiles # overwrite, zip and encrypt
mv ~/.machineconfig/dotfiles ~/.machineconfig/sync_dotfiles

# if remote doesn't exist
# rclone lsf odg1:myhome/generic_os/dotfiles.zip.encf
# if remot doesn't exists, push it for first time cloud_sx $rclone_remote ~/dotfiles -zer

echo ""
echo ""
echo "=============================== Pulling Latest From Remote ================================"
cd ~/dotfiles || exit 1
git remote remove origin
git remote add origin "$HOME/.machineconfig/sync_dotfiles"
git pull origin master

if [ $? -eq 0 ]; then
   echo ""
   echo "Pull succeeded, removing local copy of remote & pushing merged repo to remote ... "
   rm -rdf ~/.machineconfig/sync_dotfiles
   echo ""
   echo ""
   echo "===================================== Pushing new repository to remote ======================================="
   cloud_sx "$rclone_remote" ~/dotfiles -zer
else
   echo ""
   echo "Pull failed. Check the remote @ ~/.machineconfig/sync_dotfiles"
fi

# confirmation=$(read -p "Did the pull from origin merge correctly? [y/n] " confirmation)
# if [[ $confirmation == 'y' ]]; then

cd "$dir_orig" || exit 1
