#!/bin/sh

# read in configs
MYTHVERSION="`rpm -q --queryformat='%{VERSION}\n' mythtv-docs`"
if [ $? -ne 0 ]; then
    echo "mythtv-docs package not installed" 1>&2
    exit 1
fi

. /etc/mythtv/mysql.txt

if [ -z "${LocalHostName}" ]; then
    LocalHostName=`hostname`
fi

# check if we have storage directories with at least 1 video
mysql -h "${DBHostName}" -u"${DBUserName}" -p"${DBPassword}" -s \
    -e "SELECT COUNT(*) FROM recorded WHERE hostname='${LocalHostName}'" \
    "${DBName}" | egrep -q "^[1-9][0-9]*\$" || exit 0

# find orphans and print stats if found
perl /usr/local/bin/myth.find_orphans.pl \
    --dbhost="${DBHostName}" \
    --database="${DBName}" \
    --user="${DBUserName}" \
    --pass="${DBPassword}" \
    --dodelete \
    --dodbdelete | awk '
      BEGIN {
	data = "";
	ok = 0;
      }
      {
	if (/[0-9]* orphaned thumbnails with no corresponding recording/) {
	  if ($1 > 0) {
	    ok = 1;
	  }
	}
        if (/[0-9]* unknown files using [0-9]*/) {
	  if ($1 > 0) {
	    ok = 1;
          }
	}
        data = data "\n" $0
      }
      END {
	if (ok) {
	  print data;
	}
      }'
