#!/bin/sh

cd

RESTART_I3=1

SSH_TIME=${SSH_TIME:-3h}
START_EMACS=${START_EMACS:-1}

if [ -x "${DISPLAY}" ] ; then
    RESTART_I3=0
fi

if [ $# -lt 1 ] ; then
    echo "$(basename $0) [ start | end | mid ] [ -n ] [ -i ]" >&2
    exit 1
fi

check_ssh() {
    ssh-add -l >/dev/null
    SSH_ADDED=$?
    if [ $SSH_ADDED != 0 ] ; then
        ssh-add -t ${SSH_TIME}
    fi
}

start_emacs() {
    if [ $START_EMACS -eq 1 ] ; then
        i3-run i3-workspace-layout emacs-here '"1: emacs"'
    fi
}

notify() {
    send-notification "$1" "$2"
}

restart_i3() {
    if [ $RESTART_I3 -eq 1 ] ; then
        i3-msg restart
    fi
}

rsync_between() {
    LOCAL=$1
    REMOTE=$2
    rsync -aPuzb "$REMOTE" "$LOCAL"
    rsync -aPuzb "$LOCAL" "$REMOTE"
}

rsync_directories() {
    rsync_between ~/News/ swflint@boole.flintfam.org:News/
    rsync_between ~/Mail/ swflint@boole.flintfam.org:Mail/
    rsync_between ~/.elfeed/ swflint@boole.flintfam.org:Elfeed/
}

help() {
    cat <<EOF >&2
$(basename $0) [ start | end | mid ] [ -n ] [ -i ]

start :: Start the day
end   :: End the day
mid   :: Middle of the day Sync

-n    :: Don't start Emacs
-i    :: Don't restart i3
EOF
}

CMD=$1
shift

while getopts nih opt
do
    case "$opt" in
        n)
            START_EMACS=0
            ;;
        i)
            RESTART_I3=0
            ;;
        h)
            help
            exit 1
            ;;
    esac
done


if [ ${CMD} == "start" ] ; then
    check_ssh
    sync-dirs . School Projects
    rsync_directories
    restart_i3
    start_emacs
    notify "Starting Day" "On $(hostname -s)."
elif [ ${CMD} == "end" ] ; then
    check_ssh
    sync-dirs . School Projects
    rsync_directories
    notify "Ending Day" "On $(hostname -s)."
elif [ ${CMD} == "mid" ] ; then
    check_ssh
    sync-dirs org .emacs.d EBooks Documents School .ledger
    rsync_directories
    notify "Mid Day Sync" "On $(hostname -s)."
else
    help
    exit 1
fi
