#!/bin/sh

set -o errexit
set -o nounset

url="$1"
title="$2"
title=$(echo "${title}" | sed -e 's/ (matches.*$//') 

rawcontent=$(wget -q -O - "${url}")

# first try, with readability
description=$(echo "${rawcontent}" | reader "${url}" | html2md | awk '{print "> "$0}')

# not enough content? Second try without readability
# shellcheck disable=SC2312
if [ "$(echo "${description}" | wc -l)" -le 3 ]; then
  description=$(echo "${rawcontent}" | html2md | awk '{print "> "$0}')
fi

file=$(date '+%Y-%m-%d')

cd "${PROJECTS-}/vimwiki" || exit 1

# shellcheck disable=SC2250,SC2312

echo "

## $title 

> $description

<$url>
(Last access $(date '+%Y-%m-%d'))" >> ./"${file}.md"

git add "${file}.md"
git commit -m "${file}.md (auto commit)" -n > /dev/null

exit 0
