#!/bin/sh
# PR 210

EXT="_old"
DOTA_DIR="/mnt/fsuser-1/dota"
BEGIN_SCRIPT=begin_dota.sh
END_SCRIPT=end_dota.sh

if [ -f /tmp/dota_app.ok ]; then
 rm -f /tmp/dota_app.ok
fi
  
if [ -f /tmp/dota_app.ko ]; then
 rm -f /tmp/dota_app.ko
fi
    
#move to cur dir
cd /

if ! test -d $DOTA_DIR
then
#echo "no dota dir"
exit
fi

# use input file
dota=$1

report="bad archive"

final=`echo $dota | awk 'BEGIN { FS = "." } ; {print $NF}'`;
if [ "$final" = "tgz" -o "$final" = "gz" ]
then
#echo "uncompressing $dota"
gzip -d $dota
#replace extension by tar
dota=`echo $dota | sed 's/.tgz/.tar/g' | sed 's/.tar.gz/.tar/g'`
#echo "new name $dota"
fi

final=`echo $dota | awk 'BEGIN { FS = "." } ; {print $NF}'`;
if [ "$final" = "tar" ] 
then 

#echo "checking for $BEGIN_SCRIPT in $dota"
for i in `tar tf $dota`
do
script=`echo $i | grep $BEGIN_SCRIPT`;
if [ "$script" != "" ]
then
  tar xf $dota $i
  #echo Performing $i
  chmod +x $i
  ./$i
  rm $i
  fi
done

for i in `tar tf $dota` 
do

 report=""

 ## common file
 target=/tmp/$i$EXT

 scriptb=`echo $i | grep $BEGIN_SCRIPT`;
 scripte=`echo $i | grep $END_SCRIPT`;
 
 # do not install begin and end script
 if [ -z "$scriptb" -a -z "$scripte" ]
 then

   # make a copy if not a link 
   if [ -f $i -a ! -h $i ]
   then
#     echo "SAVING $i TO $target"
     mv $i $target
   fi
 
   size=`tar tvf $dota $i | awk '{print $3}'`;
 
#   echo "EXTRACTING $i ..."
   tar xf $dota $i
 
#   if test -h $i
#   then
#   echo $i is a link
#   fi

   # check size if not a link 
   if [ -f $i -a ! -h $i ]
   then
   
     # check size if tar failed 
     targetsize=`ls -l $i | awk '{print $5}'`;

     if [ $size != $targetsize ]
     then
  #     echo "problem during extraction (real size : $size, extracted size : $targetsize)"
       report="memory full"
  #     echo "RESTORING $i"
       rm $i
       mv $target $i
     fi
   fi
 fi
done

#echo "checking for $END_SCRIPT in $dota"
for i in `tar tf $dota`
do
script=`echo $i | grep $END_SCRIPT`;
if [ "$script" != "" ]
then
  tar xf $dota $i
  #echo Performing $i
  chmod +x $i
  ./$i
  rm $i
  fi
done
          
# now remove dota file
rm $dota 
fi

if [ "$report" = "" ]
then
  #echo "RES_OK"
  /bin/touch /tmp/dota_app.ok
else
  #echo "RES_KO"
  echo $report >> /tmp/dota_app.ko
fi

#echo "DOTA done"
