#!/bin/sh
#
# newsboat-maintenance - operate various tasks on urls and cache.db for newsboat
#
#   - first pass: convert http to https in urls file, if https feed is available
#   - second pass: convert urls to their new forwarded urls for 3xx http codes
#
#   feeds urls not returning xml content are tagged "_fail"
#   cache.db is also updated to refer to the new url feeds so all read/unread
#   articles and flags are preserved
#   urls file and cache.db are automatically backed up with timestamp before
#   proceeding
#
# ---
# source: https://github.com/newsboat/newsboat/blob/master/contrib/urls-maintenance.sh

# newsboat urls file and cache locations
u="${HOME%/}/.config/newsboat/urls"
db="${HOME%/}/.local/share/newsboat/cache.db"
# curl timeout for URLs probing
timeout=20
# tagfail="_fail"
useragent="Lynx/2.8.5rel.1 libwww-FM/2.14"
# where to dump headers
rss="/tmp/newsboat-rss.tmp"
headers="/tmp/newsboat-headers.tmp"

# shellcheck disable=SC2312
cp "${db}" "${db}.bak-$(date +%FT%T)"
# shellcheck disable=SC2312
cp "${u}" "${u}.bak-$(date +%FT%T)"

_replace() {
  response=$(
    curl -A "${useragent}" --connect-timeout "${timeout}" \
      --max-time "${timeout}" --write-out "%{http_code}" --silent \
      -D "${headers}" --output "${rss}" "${url2}"
  )
  if [ "${response}" = "200" ]; then
    if grep -Eq -i "content-type: .*xml" "${headers}"; then
      # escape any & found in url, this is a special character in sed
      url2=$(echo "${url2}" | sed -e 's/[&\\/]/\\&/g')
      sed -i "s,^${url},${url2}," "${u}"
      sqlite3 "${db}" "update rss_feed set rssurl='${url2}' where rssurl = '${url}' ; update rss_item set feedurl='${url2}' where feedurl='${url}'"
    else
      echo "            not replacing that feed url because feed reply is not recognised as rss content"
    fi
  else
    echo "            not replacing that feed url because feed reply code is not 200"
  fi
  [ -f "${headers}" ] && rm "${headers}"
  [ -f "${rss}" ] && rm "${rss}"
}

# replace http with https in feeds urls
feeds=$(grep -E -c "^http:" "${u}")
i=0
for url in $(shuf "${u}" | grep -E "^http:" | awk '{ print $1 }'); do
  i=$((i + 1))
  url2=$(echo "${url}" | sed 's/http:/https:/')
  printf '\r\e[K%s/%s %s\n' "${i}" "${feeds}" "${url}"
  _replace
done

# check all feeds return valid http codes
feeds=$(grep -E -c "^http" "${u}")
i=0
for url in $(shuf "${u}" | grep -E "^http" | awk '{ print $1 }'); do
  i=$((i + 1))
  # clear the line before echoing over it
  printf "\r\e[K%s/%s %s\r" "${i}" "${feeds}" "${url}"
  #echo -ne "\r\e[K$i/$feeds $url\r"
  response=$(
    curl -A "${useragent}" --connect-timeout "${timeout}" \
      --max-time "${timeout}" --write-out "%{http_code}" --silent \
      -D "${headers}" --output "${rss}" "${url}"
  )
  echo curl -A "${useragent}" --connect-timeout "${timeout}" \
    --max-time "${timeout}" --write-out "%{http_code}" --silent \
    -D "${headers}" --output "${rss}" "${url}"
  case "${response}" in
    3*)
      # url2=$(curl -A "${useragent}" -IL --silent "${url}" \
      #   | awk '/^[lL]ocation: /{ print $2 }' | head -1 \
      #   | sed 's/\r//g')
      echo "${response} [ https://httpstatuses.com/${response} ] ${url}"
      statuscode=$(cat "${DATAFILES_PATH-}"/statuscodes/"${response}")
      printf '%s\n' "${statuscode}"
      url2=$(awk '/^[lL]ocation: /{ print $2 }' "${headers}" \
        | head -1 | sed 's/\r//g')
      case "${url2}" in
        http*)
          echo "                            moved to ${url2}"
          _replace
          ;;
        /*)
          domain=$(echo "${url}" | awk -F/ '{ printf("%s//%s",$1,$3) }')
          url2="${domain}${url2}"
          echo "                            moved to ${url2}"
          _replace
          ;;
        *)
          printf "\n"
          echo "not replacing url because new feed URL is invalid or incomplete"
          ;;
      esac
      ;;
    429)
      # oops hammering too many requests
      # uncomment and adjust the sleep timer below if randomising the feeds
      # sequence was not enough to avoid "429" codes replies
      # sleep 60
      ;;
    200)
      # feed OK nothing to do
      ;;
    *)
      # everything else i.e. 000, 4xx and 5xx could be tagged _fail
      # some 2xx http codes might return valid rss feeds?
      printf "\n"
      echo "${response} [ https://httpstatuses.com/${response} ] ${url} may have problems"
      # echo "${response} [ https://httpstatuses.com/$response ] ${url} adding tag: ${tagfail}"
      # if [ ! "$(grep -E -c "^$url $tagfail" "$u")" = 1 ]; then
      #   fail tagging disabled for now
      #   sed -i "s,$url,$url $tagfail," "$u"
      # fi
      ;;
  esac
done

cleanup() {
  rm -f /tmp/newsboat-headers.tmp
  rm -f /tmp/newsboat-rss.tmp
}

trap 'cleanup' TERM QUIT

# countfile=$(mktemp)
# n=1
# shuf "${u}" \
#   | grep -v -e '^\s*#' -e '^\s*-' -e '^\s*$' -e 'exec:' \
#   | cut -d' ' -f1 \
#   | tee "${countfile}" \
#   | while read -r url; do
#     count=$(wc -l "${countfile}" | cut -d' ' -f1)
#     echo "${n}/${count} ${url}"
#     while true; do
#       response=$(curl -so /dev/null -w "%{http_code}" --connect-timeout 10 "${url}")
#       case "${response}" in
#         200) break ;;
#         429)
#           echo "Sending requests too quickly, waiting before continuing. ${url}"
#           sleep 120
#           ;;
#         *)
#           echo "${response} -- ${url}"
#           break
#           ;;
#       esac
#     done
#     n=$((n + 1))
#   done
