#!/bin/bash

# Generate a new entry for media.rec from a manually completed form, called
# 'entry'. (See more explanations in 'entry-start'.)

# Place this script in the same directory as the 'entry' file, and
# run it without argument.

# Public domain.
# Last updated 2024-01-27.
# Please report bugs to thg@gnu.org or ineiev@gnu.org.


set -e
set -o pipefail
export LANG=en_US.UTF-8
. init-tmp
. add-entry
. convert-entry
. sort-media

entry=$(make_temp entry)
entry_rec=$(make_temp entry_rec)

if [ ! -s entry ]; then
  echo 1>&2 "!!! The 'entry' file doesn't exist or is empty; exit."
  exit 1 
fi
if grep -q 'Id: xxx-000000000' entry; then
  echo 1>&2 "!!! This entry still has the default Id; exit."
  exit 1
fi

# Clean the form.

sed 's,[[:space:]]*##.*,,
     s,^[#*],,
     s,^\([A-Za-z]\+:\)[[:space:]]*\([[:print:]]\+\),\1 \2,
     /^$/d
    ' entry > $entry
       
# Check that the data is correct.

n=1
missing=""
for f in Id Type Title Language Duration License; do
   if ! data[$n]=$(grep "^$f: " $entry); then
     missing="$missing $f"
   fi
   n=$(( $n + 1 ))
done
Id=${data[1]}; Type=${data[2]}; Language=${data[4]}; Duration=${data[5]};

media=""
if grep -q '<b>Video</b>' $entry; then media="$media video"; fi
if grep -q '<b>Audio</b>' $entry; then media="$media audio"; fi
if grep -q '<b>Transcript</b>' $entry; then media="$media transcript"; fi
if grep -q '<b>Subtitles</b>' $entry; then media="$media subtitles"; fi
if grep -q '<b>Slides</b>' $entry; then media="$media slides"; fi
if  [ -n "$media" ]; then
  media="${media# }"
else
  missing="$missing Media"
fi

wrong_data=""
id=${Id#* }
if ! echo $id | grep -q '^[a-z]\+-[0-9]\{9\}$'; then
  wrong_data="${wrong_data}\n    ${Id}"
fi

type=${Type#* }
if [ ! "${type% *}" = "$type" ] ||
  [[ ! 'speech interview round-table historical movie extra' =~ "$type" ]]; then 
   wrong_data="${wrong_data}\n    ${Type}"
fi

language=$(echo $Language | sed 's,^[a-zA-Z]\+: \([a-zA-Z]\+\)\( .*\)\?$,\1,')
if [[ $language =~ " " ]]; then
  wrong_data="${wrong_data}\n    ${Language}"
fi

duration=${Duration#* }
if ! echo $duration | grep -q '^[0-9]:[0-9]\{1,2\}:[0-9]\{1,2\}$' ||
  [ "$duration" = '0:00:00' ] ; then
  wrong_data="${wrong_data}\n    ${Duration}"
else
  h=${duration%%:*} 
  m=${duration%:*} && m=${m#*:} 
  s=${duration##*:} 
  duration_errors=""
  if [ $h -gt 5 ]; then
    echo "??? Are you sure this recording is $h hours long?"
  fi
  if [ $m -gt 59 ]; then
    duration_errors="${duration_errors}    $m min is more than one hour.\n"
  fi
  if [ $s -gt 59 ]; then
    duration_errors="${duration_errors}\n    $s s is more than one minute.\n"
  fi
fi

if [ -n "$missing" ]; then
  printf 1>&2 "!!! These required fields have no data:\n   ${missing}"
  errors=1
fi
if [ -n "$wrong_data" ]; then
  printf 1>&2 "\n!!! These fields have wrong data:${wrong_data}"
  errors=1
fi
if [ -n "$duration_errors" ]; then
  printf 1>&2 "\n!!! Error(s) in the Duration field:\n${duration_errors}"
  errors=1
fi
if [ -n "$errors" ]; then
  printf 1>&2 "\nExit.\n"
  exit 1
fi


echo "${0##*\/}: Generating a new audio/video entry in rec format..."

# Extract data from the original form to complete the empty fields:
# by, year, formatted date, lang, length, media.

if [[ $id =~ "rms" ]]; then by="Richard Stallman"; fi

date=$(echo $id |
 sed 's,^[a-z]\+-\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)[0-9],\1-\2-\3,')
year=${date%%-*}

if test ! "${date%00-00}" = "$date"; then
  fdate=$(date "+%Y" -d "$year")
elif test ! "${date%-00}" = "$date"; then
  date="${date/-00/-01}"
  fdate=$(date "+%B %Y" -d "$date")
else
  fdate=$(date "+%B %d, %Y" -d "$date")
fi

case $language in
    English) lang="en";;
    Spanish) lang="es";;
     French) lang="fr";;
  Malayalam) lang="ml";;
          *) lang="other";;
esac

duration=""
if [ "$h" != "0" ]; then
  duration=${h}h
  hs=$(( $h * 3600 ))
fi
if [ "$m" != "0" ]; then
  duration="$duration ${m}min"
  ms=$(( $m * 60 ))
fi
if [ "$s" != "0" ]; then
  duration="$duration ${s}s"
fi

ts=$(( $hs + $ms + $s ))
if   [ $ts -gt 2700 ]; then tlength='long'
elif [ $ts -lt  600 ]; then tlength='short'
else                        tlength='medium'
fi

# Create missing entries.

grep -q '^Year:'   $entry || sed -i '/^Id:/      aYear:' $entry
grep -q '^Lang:'   $entry || sed -i '/^Type:/    iLang:' $entry
grep -q '^Length:' $entry || sed -i '/^Type:/  aLength:' $entry
grep -q '^Media:'  $entry || sed -i '/^Length:/ aMedia:' $entry
if ! grep -q '^Date:' $entry; then
  if grep -q '^Location:' $entry; then
    sed -i '/^Location:/ iDate:' $entry
  else
    sed -i '/^Language:/ iDate:' $entry
  fi
fi

# Add the derived data to the form and convert to rec format.

sed "s,^Year:.*$,Year: $year,
     s,^Lang:.*$,Lang: $lang,
     s,^Length:.*$,Length: $tlength,
     s,^Media:.*$,Media: $media,
     s,^By:$,By: $by,
     s|^Date:.*$|Date: $fdate|
     s,^Duration:.*$,Duration: $duration,
     /^[a-zA-Z]\+:/! s,^,+ ,
    " $entry  > $entry_rec

# Convert entry.rec to entry.html and add it to media.html,
# then add entry.rec to media.rec.

add_entry $entry_rec

# Make sure this entry isn't reused by mistake.
cp entry entry-old
cp entry-start entry

echo "Done."
exit 0
