#!/bin/sh -e
#
# si - open one of the existing scripts to edit
# dependencies: fzf

sdir=$(cd "$(dirname "$0")" >/dev/null 2>&1 && pwd) && cd "${sdir}" || exit 1

if [ -z "$1" ]; then
  file=$(find -L "${sdir}"/* -type f -print0 | xargs -0 ls -t \
    | sed "s|${sdir}/||" \
    | fzf --ansi --reverse --height=40% --margin=5% \
      --exact --print-query \
      --tiebreak=length,begin,index --multi \
      --bind="alt-e:execute(${EDITOR:-vi} {+})" \
      --bind='ctrl-y:execute-silent(echo {+} | pbcopy)' \
      --bind='?:toggle-preview' \
      --preview='bat --style=snip --color=always {}' \
      --preview-window='up,60%,border-line,hidden' | tail -n 1)
  [ -n "${file-}" ] || exit 0
else
  file="$1"
fi

if [ -f "${sdir}/${file}" ]; then
  ${EDITOR:-vi} "${sdir}/${file}"
else
  extension="${file##*.}"
  case "${extension}" in
    awk)
      printf '#!/usr/bin/env awk -f\n\n' >"${sdir}/${file}" \
        && chmod +x "${sdir}/${file}" && ${EDITOR:-vi} "${sdir}/${file}"
      ;;
    sed)
      printf '#!/usr/bin/env sed -f\n\n' >"${sdir}/${file}" \
        && chmod +x "${sdir}/${file}" && ${EDITOR:-vi} "${sdir}/${file}"
      ;;
    sh)
      printf '#!/usr/bin/env sh\n\nset -e\n\n' >"${sdir}/${file}" \
        && chmod +x "${sdir}/${file}" && ${EDITOR:-vi} "${sdir}/${file}"
      ;;
    py)
      printf '#!/usr/bin/env python3\n\n' >"${sdir}/${file}" \
        && chmod +x "${sdir}/${file}" && ${EDITOR:-vi} "${sdir}/${file}"
      ;;
    pl)
      printf '#!/usr/bin/env perl\nuse strict;\nuse warnings;\n' >"${sdir}/${file}" \
        && chmod +x "${sdir}/${file}" && ${EDITOR:-vi} "${sdir}/${file}"
      ;;
    *)
      printf '#!/bin/sh -e\n\n' >"${sdir}/${file}" \
        && chmod +x "${sdir}/${file}" && ${EDITOR:-vi} "${sdir}/${file}"
      ;;
  esac
fi
