#!/bin/bash
#
# Modify to suit
CONFIGDIR='shortcut'
RECORDINGS='/volume1/TV/'
JSONFILE="/tmp/import.json"
USER=admin
PASS=secret

echo "Scanning logs and recordings"

COUNT=0

for FILE in $(find $RECORDINGS -type f -name "*.ts" -o -name "*.mkv") ; do
    FILENAME=$(basename $FILE)
    FTYPE=""
    NAME=${FILENAME%.ts}
    if [ "$FILENAME" = "$NAME" ]; then
      NAME=${FILENAME%.mkv}
      if [ "$FILENAME" != "$NAME" ]; then
        FTYPE=mkv
      fi
    else
      FTYPE=ts
    fi
    if [ "$FTYPE" = "ts" ] || [ "$FTYPE" = "mkv" ]; then
      LOGFILE=$(grep ${FILE} $CONFIGDIR/dvr/log/* | cut -d ':' -f 1)
      if [ "$LOGFILE" ]
      then
        echo "Preparing to import $(basename ${FILE}) with log $(basename ${LOGFILE})"
        echo -n "conf=" > "$JSONFILE"
        cat "$LOGFILE" >> "$JSONFILE"
        echo "Sending create command for \"$FILENAME\""
        if curl -q --data @"$JSONFILE" "http://$USER:$PASS@localhost:9981/api/dvr/entry/create" ; then
          echo "Imported \"$FILENAME\" successfully"
        fi
        echo
      else
        echo "Failed to import $(basename ${FILE}) - no log"
        #tvhimport.sh $COMMAND "${FILE}"
        ls -lahF $CONFIGDIR/dvr/log/
        exit 0
      fi
#      let COUNT++
#      if [ $COUNT -gt 5 ]; then
#        exit 0
#      fi
    fi
    sleep 5
done
