# Convert a media entry from rec format to HTML, and
# add it to media.rec and media.html.

# Called from av-create, av-edit and avgen.

# Public domain.
# Last updated 2022-11-10.
# Please report bugs to thg@gnu.org or ineiev@gnu.org.


function add_entry () {

  media_html=$(make_temp media_html)
  entry_html=$(make_temp entry_html)

  if [ -s "$1" ]; then
    id=$(grep 'Id: ' $1 | sed 's,^Id: ,,')
    echo "${0##*\/}: Adding $id to media.html and media.rec..."
    cp ../media.html $media_html

    # Check that the new id isn't already used in media.html.
    if grep -q "id=.$id." $media_html; then
      echo "*** $id is already in media.html."
    # If it isn't, convert entry.rec to HTML, add it to the list, and sort entries.
    else
      convert_entry $1 $entry_html
      cat $entry_html >> $media_html
      sort_media $media_html
      cp $media_html ../media.html
      echo "*** $id was (re)added to media.html."
    fi

    # Same thing with media.rec, but without sorting.
    if grep -q "Id: $id" media.rec; then
      echo "*** $id is already in media.rec."
    else
      sed -i '1 s,^,\n,' $1
      sed "/ADD NEW ENTRY HERE/ r $1" media.rec  > /tmp/f &&
      mv /tmp/f media.rec
      echo "*** $id was added to media.rec."
    fi

  else
    echo 1>&2 "!!! Nothing to add; exit."
    exit 1
  fi
}
