#!/bin/sh

USER=sdk
DOMAIN=home.codevoid.de
RPATH=~/make-web/src

usage() {
    printf 'Usage: %s <option> <file.ext>\n' "$TYPE";
    printf 'Options:  new     - create new %s file\n' "$TYPE"
    printf '          ls      - list %ss\n' "$TYPE"
    printf '          edit    - edit %s file\n' "$TYPE"
    printf '          rm      - delete %s file\n' "$TYPE"
}

chkfile() {
    [ ! -z "$2" ] \
        && usage \
        && exit 2
}


new() {
    chkfile
    printf "New Entry:\n"
    printf "$1\n" | tr '_' ' ' > "/tmp/tmp-$date-$1" && \
    vim "/tmp/tmp-$date-$1" \
    && scp "/tmp/tmp-$date-$1" \
        $USER@$DOMAIN:"$RPATH/posts/$date-$1"
    makeblog
}
delete() {
    chkfile
    printf "Delete Entry: $1\n"
    ssh $USER@$DOMAIN "rm -vf $RPATH/posts/$1"
    makeblog
}

list() {
    printf "Blog Index:\n"
    ssh $USER@$DOMAIN "find $RPATH/posts -type f -maxdepth 1 \
                    -exec printf '{}|' \; -exec head -1 '{}' \; \
                    | sed 's,.*/,,'| sort | column -s'|' -t "
}

edit() {
    chkfile
    printf "Edit Entry:\n"
    [ -z $1 ] && printf "Usage: editblog <file.ext>\n" && return
    printf "Opening $1\n"
    local date=$(date +"%Y-%m-%d")
    scp -q $USER@$DOMAIN:"$RPATH/posts/$1" "/tmp/tmp-$1" && \
    vim "/tmp/tmp-$1" && \
    scp -q "/tmp/tmp-$1" $USER@$DOMAIN:"$RPATH/posts/$1" && \
    rm "/tmp/tmp-$1" && \
    printf "Saved $1\n"
    makeblog
}

makeblog() {
    ssh $USER@$DOMAIN "cd ~/make-web && make install"
}

date=$(date +"%Y-%m-%d")
dash="------------------------------------------------------------------------"

### MAIN PROGRAM ###

# the filename is used as type
case $0 in
    *blog) TYPE=blog;
        ;;
    *journal) TYPE=journal;
        ;;
    *) printf 'Filename must be "blog" or "journal"\n'; exit 1;
        ;;
esac

# where should the files go?
[ "$TYPE" == "blog" ] \
    && DIR=posts
[ "$TYPE" == "journal" ] \
    && DIR=journal

case $1 in
    new) new $2;
        ;;
    edit) edit $2;
        ;;
    ls) list;
        ;;
    rm) delete $2;
        ;;
    *)  usage;
        exit 2;
        ;;
esac
