verifyPicture

#!/bin/bash

#Permet de vérifier qu'une image distante
#est de type JPEG ou GIF non animé.
#Montre entre autres l'usage de wget
#et des gestionnaires de signaux

unset POSIXLY_CORRECT

export TEMPORARY_DIR=/tmp/
export LOOP_STRING="NETSCAPE2\.0"
export MAX_SIZE=4096

exit_handler()
{
    PID2=`ps --format="pid command" | grep wget | grep $2 | gawk '{print $1}'`
    if [ "$PID2" = "$1" ]
    then
      kill $PID2
    fi
    rm -f $2
    echo "INTERRUPTED"
    exit 1
}

check_file()
{
  temporary_file=`basename $1`
  timestamp=`date "+%s"`
  image_file=$TEMPORARY_DIR$temporary_file.$timestamp
  wget -O $image_file -r --ignore-length $1 >/dev/null 2>&1 &
  PID=`ps --format="pid command" | grep wget | grep $image_file | gawk '{print $1}'`
  if [ -n "$PID" ]
  then
    trap "exit_handler $PID $image_file" 0
    while ps $PID >/dev/null 2>&1
    do
      size=`ls -l $image_file | gawk '{print $5}'`
      if expr "$size" ">" $MAX_SIZE >/dev/null 2>&1
      then
        echo KILLING $PID
        kill $PID >/dev/null 2>/dev/null
        break
      fi
      sleep 1
    done
    trap - 0
  fi
  if [ -f $image_file ]
  then
    file_type=`file $image_file | cut -f 2 -d ' '`
    if [ "$file_type" != GIF -a "$file_type" != JPEG ]
    then
      echo "TYPE"
      result=1
    else
      size=`ls -l $image_file | gawk '{print $5}'`
      if expr "$size" ">" $MAX_SIZE >/dev/null 2>&1
      then
        echo "BIG"
        result=1
      else
        if grep $LOOP_STRING $image_file >/dev/null 2>&1
        then
          echo "ANIMATED"
          result=1
        else
          echo "OK"
          result=0
        fi
      fi
    fi
  else
    echo "BAD"
    result=1
  fi

  rm -f $image_file
  return $result
}

check_file $1 2>/dev/null