#!/bin/sh

# 4D client self upgradeable script

# parameters 1 old application folder 
# 2 application name (build name, different from $8 if the user changed the application name)
# 3 decompressing folder
# 4 temporary folder
# 5 trash  
# 6 script name  
# 7 old client process id   
# 8 application name (old application name, name choosed by the user)   

# echo `pwd` > a.txt
# echo $1 "P2" $2 "P3" $3 "P4" $4 "P5" $5 "P6" $6 "P7" $7 "P8" $8 "P9" $9 >> a.txt

sa=".app"
appname=$2

if [ -n "$8" ]
 then
   oldname=$8
 else
   oldname=$2
fi

# waiting old client to quit
count=`ps -p $7 | wc -l`
j=""
while [[ $count -gt 1 ]] && [[ $j -lt 30 ]]
 do
    sleep 0.2
    count=`ps -p $7 | wc -l`
    j=$(($j+1))
 done

if [ $count -le 1 ]
 then 
  #Restore server settings
  server="Contents/Database/EnginedServer.4Dlink"
  if [ -a "$oldname$sa/$server" ]
   then
    cp -f "$oldname$sa/$server" "$4/$3/$appname$sa/$server"
  fi

  # moving old client to trash
  # there is already in the trash an item (a folder or a file) with our client's name? 
  if [  -e  ~/.Trash/"$oldname$sa" ]
   then 
    i=""
    sc="copy"

    # looking for a name like our_clientXXX that is not already in the trash 
    while [  -e  ~/.Trash/"$oldname $sc $i$sa" ]
	do
      i=$(($i+1))
    done

    echo $i
    echo ~/.Trash/"$oldname $sc $i$sa"
    mv "$oldname$sa" ~/.Trash/"$oldname $sc $i$sa"
   else
    mv "$oldname$sa" ~/.Trash/"$oldname$sa"
  fi

  #new client replace the old one
  mv "$4/$3/$appname$sa" "$oldname$sa"

  # temporary folder removing
  rm -dfR "$4"

  # script removing from 4D Extensions
  # rm  -f   "$oldname$sa/Contents/4D Extensions/$6"

  # new client executable execute permissions
  chmod a+x "./$oldname$sa/Contents/MacOS/"*
  
  # new client launching
  open "./$oldname$sa"

fi

