#!/bin/bash

if ! [ -x "$(command -v git)" ]; then
    printf "please install git!\n"
    exit 1
fi

if ! [ -d "$NOTE_DIR" ]; then
    printf "please setup notes using \$NOTE_DIR!\n"
    exit 1
fi

function got_to_notes {
    log "changing to note dir: $NOTE_DIR"
    cd "$NOTE_DIR" || (echo "can't find notebook dir" && exit 1)
}

function go_back {
    log "returning user"
    cd - || (echo "failed to return" || exit 1)
}

function sync {
    log "syncing"
    save
    pull
    push
}

function pull {
    log "pulling remote"
    got_to_notes
    git pull || exit 1
    go_back
}

function push {
    log "pushing to remote"
    got_to_notes
    git push
    go_back
}

function save {
    log "saving all changes"
    got_to_notes
    git add .
    git commit -am "saving up to $(date)"
    go_back
}

function log {
    echo "zet::log $(log_time): $1"
}

function error {
    echo "zet::error $(log_time): $1"
}

function log_time {
    date -u +"%Y-%m-%dT%H:%M:%SZ"
}

function help {
    echo "zet::help: zet sync -- save, pull, push"
    echo "zet::help: zet pull -- pull from remote"
    echo "zet::help: zet push -- push to remote"
    echo "zet::help: zet save -- save all changes"
}

# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
    # call arguments verbatim
    "$@"
else
    # Show a helpful error
    echo "'$1' is not a known option" >&2
    exit 1
fi
