#!/bin/ksh
. $HOME/.bin/_config

_rdir=$1

list() {
    _dir="$1"
    _sel="$(ssh $USER@$DOMAIN "cd \"$_dir\" && ( printf 'GO BACK\nNEW FILE\n'; ls -lt .; )" \
           | egrep -v ^total | fzf)"

    [ $? -ne 0 ] && exit;

    case "$_sel" in
        "NEW FILE") newfile "$_dir" ;;
        "GO BACK") list "$_dir/.." ;;
        *) dofile "$_dir" "$_sel" ;;
    esac
    list "$_dir"
}

dofile() {
    _dir="$1"
    _sel="$2"
    _do="$(printf 'EDIT\nDELETE\nDOWNLOAD\n' | fzf)";
    [ $? -ne 0 ] && exit;

    _entry=$(printf '%s' "$_sel" | tr -s ' ' | cut -d" " -f9-)

    if printf '%s' "$_sel" | egrep ^d;
    then
        list "$_dir/$_entry"
    else
        case "$_do" in
            "EDIT") vim "sftp://$USER@$DOMAIN/$_dir/$_entry" ;;
            "DELETE") ssh $USER@$DOMAIN "rm /$_dir/$_entry" ;;
            "DOWNLOAD") scp "$USER@$DOMAIN:/$_dir/$_entry" . ;;
            "GO BACK") list "$_dir" ;;
        esac
    fi
}

newfile() {
    _dir="$1"
    printf 'Filename (%s)? ' "$(date +%Y-%m-%d-)"
    read name;
    vim "sftp://$USER@$DOMAIN/$_dir/$name"
}

list "${_rdir:=$RPATH}"
