#!/bin/sh

DBUSER=root;
DBPWD=
DBNAME=mythconverg


TMPFILE=/tmp/tmp.png

case "$1" in

 start)

  WERTE=`echo "SELECT playername FROM gameplayers" | mysql -B --database=$DBNAME --password=$DBPWD --user=$DBUSER -N`;

  for player in $WERTE
   do 
 
    ROMPATH=`echo "SELECT rompath FROM gameplayers WHERE playername = '$player'" | mysql -B --database=$DBNAME --password=$DBPWD --user=$DBUSER -N`
    COMMANDLINE=`echo "SELECT commandline FROM gameplayers WHERE playername = '$player'" | mysql -B --database=$DBNAME --password=$DBPWD --user=$DBUSER -N`
    EXTENSIONS=`echo "SELECT extensions FROM gameplayers WHERE playername = '$player'" | mysql -B --database=$DBNAME --password=$DBPWD --user=$DBUSER -N`
    SCREENSHOTS=`echo "SELECT screenshots FROM gameplayers WHERE playername = '$player'" | mysql -B --database=$DBNAME --password=$DBPWD --user=$DBUSER -N`
    
    cmdpfad=$(dirname "$(echo $COMMANDLINE | cut -d "-" -f 1)")
    cmdprgname=$(basename "$(echo $COMMANDLINE | cut -d "-" -f 1)")
    cmdparameter=${COMMANDLINE:$((`echo "$cmdpfad" | wc -m`+`echo "$cmdprgname" | wc -m`-1)):`echo "$COMMANDLINE" | wc -m`}
    cmdrun=`echo "$cmdpfad/$cmdprgname"`
    
    if [ "$ROMPATH" ]; then
      #if [ "$player" = "GBA" ]; then
        for i in $ROMPATH/*.*
         do
         COMMAND="start-stop-daemon --exec $cmdrun --start --background -- $cmdparameter" 
         $COMMAND "$i"      
         path="`expr "$i" : '\(.*\)/'`"                  # get file path (if any)
         name="`expr "//$i" : '.*/\([^/]*\)'`"           # remove path to file
         suffix="`expr "$name" : '.*\.\([^./]*\)$'`"     # extract last suffix
         name="`expr "$name" : '\(.*\)\.[^.]*$'`"        # remove last suffix
         picname=$name.png

        sleep 10
      
        scrot --quality 1 $TMPFILE
        mv $TMPFILE "$SCREENSHOTS/$picname"
        killall -9 $cmdrun
        sleep 1
        done
      #fi
    fi
  done
  ;;
  
  *)
  echo ""
  echo "This is a Script to generate Screenshots for your Emulators, wich"
  echo "you have set up in MythTV automaticaly. It uses the program scrot"
  echo "to generate the screenshot."
  echo ""
  echo "To run you had to enter: emulator_screenshots start"
  echo "Bevor running, check the username and passwort in the script"
  echo "Also the timeout until the screenshot is taken can be adjusted"
  ;;
esac
