#!/bin/sh -e
#
# convert twtxt.txt to atom file

# some help can't hurt
help() {
  printf "usage:\n"
  printf "\t%s -n <nick> -u <feed url> -t <feed title> -x <twtxt.txt url> twtxt.txt\n" "${0##*/}"
  exit 1
}

# make sure variables to check later if user set them
nick=""
url=""
title=""
twtxturl=""

# use getopt to get options
while getopts ':n:u:t:x:h' opt; do
  case "${opt}" in
    n) nick="${OPTARG}" ;;
    u) url="${OPTARG}" ;;
    t) title="${OPTARG}" ;;
    x) twtxturl="${OPTARG}" ;;
    h)
      printf "%s -n <nick> -u <feed url> -t <feed title> -x <twtxt.txt url> twtxt.txt\n" \
        "${0##*/}"
      exit 0
      ;;
    *)
      printf "%s: Unrecognized option: '-%c'\n" "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
  esac
done
# skip options in argument index so $1 is twtxt.txt
shift "$((OPTIND - 1))"

# abort if user forgot a parameter
test -z "${nick}" && help
test -z "${url}" && help
test -z "${title}" && help

domain=$(printf '%s' "${url}" | awk -F/ '{ print $3 }')

# header template of the atom
HEADER="<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'>
<id>${url}</id>
<title>${title}</title>
<link rel='self' type='application/atom+xml' href='${url}' />
<author><name>${nick}</name></author>
"

# get the last entry to set last time atom was updated
LAST="$(awk 'END { print $1 }' "$1")"

# Let's output the beginning
printf '%s' "${HEADER}"
printf '<updated>%s</updated>\n' "${LAST}"

# grep remove comments and empty lines and loop over twtxt.txt lines
grep -Ev '^#|^$' "${1}" | while read -r TS MSG; do
  # Can't have ]]> in CDATA
  ESCAPED="$(printf "%s" "${MSG}" | awk '{gsub("]]>", "]]]]><![CDATA[>")}1')"
  # output the entry
  printf '<entry>\n'

  # ID must be unique
  # shellcheck disable=SC2046,SC2312
  printf '<id>tag:%s,%s:twtxt%s</id>\n' "${domain}" \
    $(printf '%s' "${TS}" | cut -d'T' -f1) \
    $(printf '%s' "${TS}" | tr -cd '\[^[:digit:]\]')

  printf '<title type="text"><![CDATA[%s]]></title>\n' "${ESCAPED}"
  printf '<updated>%s</updated>\n' "${TS}"
  printf '<content type="text"><![CDATA[%s]]></content>\n' "${ESCAPED}"
  printf '<link rel="alternate" type="text/plain" href="%s" />\n' "${twtxturl}"
  printf '</entry>\n'
done

printf '%s' '</feed>' 
exit 0
