#!/bin/csh -f

if($#argv != 1 && $#argv != 2) then
  echo "USAGE: ima-checkimgno imadir <outfile>"
  exit 1;
endif

set imadir  = $argv[1];
if( ! -e $imadir ) then
  echo "ERROR: $imadir does not exist"
  exit 1;
endif

if($#argv == 2) then
  set outfile = $argv[2];
  set outdir = `dirname $outfile`;
  mkdir -p $outdir
else
  set outfile = /dev/null
endif

echo "Checking $imadir" |& tee -a $outfile
date                    |& tee -a $outfile

pushd $imadir > /dev/null

set tmpfile = /tmp/ima-checkimgno-$$
rm -f $tmpfile
touch $tmpfile

echo "Parsing files names ... "
ima-parse-name * > $tmpfile
if($status) then
  echo "ERROR: ima-parsename failed" |& tee -a $outfile
  rm -f $tmpfile
  exit 1;
endif

set imgnolist  = `cat $tmpfile | awk '{print $3}' | sort -n`;
set firstimgno = $imgnolist[1];
set lastimgno  = $imgnolist[$#imgnolist];

echo "Found $#imgnolist images"     |& tee -a $outfile
echo "First Image No: $firstimgno"  |& tee -a $outfile
echo "Last  Image No: $lastimgno"   |& tee -a $outfile

echo "Searching for missing image numbers ... "
set missing = ();
@ imgno = 1;
while ( $imgno <= $lastimgno )
  set match = `cat $tmpfile | awk '{print $3}'  | grep -x $imgno | wc -l`;
  if($match < 1) set missing = ($missing $imgno);
  @ imgno = $imgno + 1;
end

if($#missing == 0) then
  echo "No missing images found" |& tee -a $outfile
else
  foreach imgno ($missing)
    echo "$imgno" |& tee -a $outfile
  end
endif

date |& tee -a $outfile

rm -f $tmpfile


exit 0;
