#!/bin/sh -e
#
# bt - bat latest with fzf

find=$(command -v gfind || echo find)

case "$#" in
  1)
    case "$1" in
      *[!0-9]*)
        ${find} -L -- "$1" -path '*/.git' -prune -o -type f -exec ls -At -- {} + \
          | fzf --delimiter="/" --with-nth=-2,-1 --tiebreak=index \
            --preview-window='nohidden:right' \
            --preview='bat --color=always --style=snip {}' \
            --bind="enter:become(cat {} || bat --color=always --theme=ansi {})" \
            --bind="ctrl-y:execute-silent(ruby -e 'puts ARGV' {+} | pbcopy)"
        ;;
      *)
        # if is-num "$1"; then
        # ${find} . -path '*/.git' -prune -o -type f -exec  ls -Art {} + \
        # ${find} . -path '*/.git' -prune -o -type f -exec ls -t {} + \
        # find . -path '*/.git' -prune -o -type f -exec ls -tp -- {} + \
        ${find} . -path '*/.git' -prune -o -type f -printf "%T+ %p\n" \
          | sort -r \
          | head -n "$1" \
          | awk '{ print $2 }' \
          | fzf --delimiter="/" --with-nth=-1 --tiebreak=begin \
            --preview-window='nohidden:right' \
            --preview='bat --color=always --style=snip {}' \
            --bind="enter:become(bat --color=always --theme=ansi {})" \
            --bind="ctrl-y:execute-silent(ruby -e 'puts ARGV' {+} | pbcopy)"
        ;;
    esac
    ;;
  2)
    case "$1" in
      *[!0-9]*)
        num="$2"
        pat="$1"
        ;;
      *)
        num="$1"
        pat="$2"
        ;;
    esac
    ${find} -L "${pat}" -path '*/.git' -prune -o -printf "%T+ %p\n" \
      | sort -r \
      | head -n "${num}" \
      | awk '{ print $2 }' \
      | fzf --delimiter="/" --with-nth=-1 --tiebreak=index \
        --preview-window='nohidden:right' \
        --preview='bat --color=always --style=snip {}' \
        --bind="enter:become(bat --color=always --theme=ansi {})" \
        --bind="ctrl-y:execute-silent(ruby -e 'puts ARGV' {+} | pbcopy)"
    ;;
  *)
    # ${find} -L . -path '*/.git' -prune -o -exec ls -At -- {} + | head -n 100 \
    ${find} . '(' -path '*.git' ')' -prune -o -type f -print0 \
      -exec ls -Atp -- {} + \
      | sed "s|${PWD}/||" \
      | fzf \
        --preview='bat --color=always --style=snip {}' \
        --preview-window='default:border-left,+{2}+3/3,~3' \
        --bind="enter:become(bat --color=always --theme=ansi {})" \
        --bind="ctrl-y:execute-silent(ruby -e 'puts ARGV' {+} | pbcopy)"
    ;;
esac
