#!/bin/sh -e
#
# add `:name <name>` at top to specify name
# source: https://github.com/meain/dotfiles/blob/master/scripts/.local/bin/random

DIR="${VIME_PATH-}"
mkdir -p "${DIR}"
if [ "$1" = "list" ]; then
    ls -t "${DIR}" | {
        while read -r line; do
            title="$(grep '^:name' "${DIR}/${line}" | head -n 1 | sed 's|:name ||')"
            echo "${line}   ${title}"
        done </dev/stdin
    } |
        ,picker -p "Select file" --preview "cat '${DIR}/{1}'" | awk '{print $1}' | xargs -I{} "${EDITOR:-vi}" "${DIR}/{}"
elif [ "$1" = "last" ]; then
    ls -t "${DIR}" | head -n 1 | xargs -I{} "${EDITOR:-vi}" "${DIR}/{}"
elif [ "$1" = "rename" ]; then
    printf "New name: "
    read -r DIR
    ls -t "${DIR}" | {
        while read -r line; do
            title="$(grep '^:name' "${line}" | head -n 1 | sed 's|:name ||')"
            echo "${line}  ${title}"
        done </dev/stdin
    } |
        ,picker -p "Select file" --preview "cat '${DIR}/{1}'" |
        awk '{print $1}' | xargs -I{} mv "${DIR}/{}" "${DIR}/${REPLY}"
else
    ${EDITOR:-vi} "${DIR}/_$(xxd -l2 -ps /dev/urandom)"
fi
