#!/usr/bin/env sh
# Read
# extended version of one-liner script to read wallabag articles in shell
# "wallabag list -n | head -n-1 | tail -n+2 | fzf | sed -e 's/^ //' |  cut -f1 -d' ' | xargs wallabag show | ifne less"

WALLR_FILTER=${WALLR_FILTER:-all}
WALLR_READER=${WALLR_READER:-$PAGER}
WALLR_FZF_OPTS=${WALLR_FZF_OPTS:-"--border"}
WALLR_MARKREAD=true

# get listing of all (read/unread/starred/all) wallabag articles
get_articles() {
  if [ "$WALLR_FILTER" = "all" ]; then
    wallabag list
  elif [ "$WALLR_FILTER" = "starred" ]; then
    wallabag list -s
  elif [ "$WALLR_FILTER" = "unread" ]; then
    wallabag list -n
  else
    wallabag list -r
  fi
}

# return the ID of article from listing version
get_id() {
  [ -z "$1" ] && exit 1
  echo "$1" | head -n-1 | tail -n+2 | fzf "${WALLR_FZF_OPTS}" | sed -e 's/^ \+//' | cut -f1 -d' '
  exit 1
}

# grab content of article with ID passed in as parameter
get_content() {
  [ -z "$1" ] && exit 1
  wallabag show "$1" | tail -n+2
}

# open article in browser
open_link() {
  [ -z "$1" ] && exit 1
  wallabag open "$1"
}

# mark article read
mark_read() {
  [ -z "$1" ] && exit 1
  wallabag update --read "$1"
}

check_missing_reqs() {
  if command -v fzf >/dev/null && command -v wallabag >/dev/null; then
    false
  else
    true
  fi
}

main() {
  arts=$(get_articles "$WALLR_FILTER")
  id="$(get_id "$arts")"

  if [ "$WALLR_READER" = "BROWSER" ]; then
    open_link "$id"
  else
    get_content "$id" | "$WALLR_READER"
    if "$WALLR_MARKREAD"; then
      mark_read "$id"
    fi
  fi
}

show_help() {
  printf "%s\n" \
    "" \
    " reader       Read wallabag articles in the terminal." \
    "" \
    " Usage: reader [-horqsen] " \
    "" \
    " Options:" \
    "" \
    "     -o                                  Open selected file in browser." \
    "" \
    "     -e                                  Open selected file in editor." \
    "" \
    "     -r                                  List only read articles." \
    "" \
    "     -s                                  List only starred articles." \
    "" \
    "     -n                                  List only unread articles." \
    "" \
    "     -q                                  Do not mark articles opened as read." \
    "" \
    "     -h                                  Print out this help." \
    ""
}

while getopts "h?qnorse" opt; do
  case "$opt" in
  h | \?)
    show_help
    exit 0
    ;;
    # v)  verbose=1
    # ;;
  n)
    WALLR_FILTER="new"
    ;;
  r)
    WALLR_FILTER="read"
    ;;
  s)
    WALLR_FILTER="starred"
    ;;
  e)
    WALLR_READER="$EDITOR"
    ;;
  o)
    WALLR_READER="BROWSER"
    ;;
  q)
    WALLR_MARKREAD="false"
    ;;
  esac
done
shift $((OPTIND - 1))

if check_missing_reqs; then
  echo "Requires wallabag-cli and fzf executable on path to work." 1>&2
  exit 1
fi
main "$@"