#!/bin/bash

# Replace an entry in media.html with the media.rec version.

# This script is used when an entry has been edited in media.rec. It extracts
# the edited entry, and removes the old version from media.html. Then it calls
# 'av_add' to insert the edited entry into media.html.

# Run the script with the id of the entry as argument:    av-edit ID

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


set -e
set -o pipefail
. init-tmp
. add-entry
. convert-entry
. sort-media

id=$1

if test -z "$id"; then
  echo "*** Please enter the id of the entry that has been edited in media.rec."
  read id
fi

if [ -n "$id" ]; then
  id_attr="id=\"$id\""

  entry_rec=$(make_temp entry_rec)

  awk -v pattern=$id_attr '
    BEGIN { RS = ORS = "\n\n"; found = 0 }
    {
      if (ret = match( $0, pattern )) {
        $0 = ""
        print pattern " was removed from media.html."
        found = ret
      }
      print $0 > "/tmp/f"
    }
    END {
      if ( found == 0 ) print pattern " was not found in media.html."
    }' ../media.html

  mv /tmp/f ../media.html

  if grep -q "$id" media.rec; then
    sed -n "/^Id: $id/,/^$/p" media.rec > $entry_rec
    echo "$id was extracted from media.rec."
  else
    echo 1>&2 "!!! $id was not found in media.rec; exit."
    exit 1
  fi
else
  echo 1>&2 '!!! Missing id; exit.'
  exit 1
fi

add_entry $entry_rec

exit 0
