#!/bin/bash

function get_version ()
{
  cd $1
  echo "load 'DodontoFServer.rb';print \$version" |ruby
}

function pg_exit ()
{
  echo "Cleanup work directory"
  \rm -rf $1
  exit $2
}

WORKDIR=/tmp/dodontof_update.`date "+%Y%m%d"`.$$
LOG=/tmp/dodontof_update.`date "+%Y%m%d"`.$$.log

if [ $# != 2 ]
then
  echo "Usage $0 file targetdir"
  echo "Ex) $0 DodontoF_Ver.1.33.02.zip /home/foo/public_html/DodontoF/"
  exit 0
fi

ARCHIVE=$1
PWD=`pwd`
TARGET=`echo $2|awk -vpwd="${PWD}/" '{if ($1 !~ /^\//) sub(/^/,pwd);print}'| sed -e "s/\/$//"`

CURRENTVER=`get_version $TARGET`
BACKUPDIR=${TARGET}.bkup.`date +"%Y%m%d"`.$$

if [ ! -n ${CURRENTVER} ]
then
  echo "No current dodontoF in ${TARGET} directory."
  exit 1
fi

echo "Dodontof update archive is ${ARCHIVE}"
echo "Target directory is ${TARGET}"
echo "Target current dodontof version is ${CURRENTVER}"
echo ""
echo "Is it correct?<y/n>"
read YESNO

if [ ${YESNO} != "y" ]
then
  echo "aborted."
  exit 0
fi

> ${LOG}

echo "Backup Current dodontof to ${BACKUPDIR}" |tee -a $LOG
if [ ! -d ${BACKUPDIR} ]
then
  cp -av ${TARGET} ${BACKUPDIR} >>$LOG 2>&1
else
  echo "${BACKUPDIR} already exist."
  pg_exit ${WORKDIR} 1
fi

echo "----------------------------" >>$LOG
echo "Extracting archive file to work dir." |tee -a $LOG
mkdir ${WORKDIR}
unzip ${ARCHIVE} -d ${WORKDIR} >>${LOG} 2>&1
if [ $? != 0 ]
then
  echo "Extract archive file failed. See logfile($LOG)"
  pg_exit ${WORKDIR} 1
fi

NEWVER=`get_version ${WORKDIR}/DodontoF`

echo "----------------------------" >>$LOG
echo "Converting ruby and perl path." |tee -a $LOG
cd ${WORKDIR}/DodontoF
find ./ -name '*.rb' -type f |while read FILE
do
  echo "Converting ${FILE}" >>$LOG
  mv ${FILE} ${FILE}.orig
  cat ${FILE}.orig |sed "1s#.*#\#\!`which ruby` -Ku#" >${FILE}
done

cd ${WORKDIR}/DodontoF
find ./ -name '*.pl' -type f |while read FILE
do
  echo "Converting ${FILE}" >>$LOG
  mv ${FILE} ${FILE}.orig
  cat ${FILE}.orig |sed "1s#.*#\#\!`which perl`#" >${FILE}
done

echo "----------------------------" >>$LOG
echo "Copying other contents" |tee -a $LOG
cd ${WORKDIR}/DodontoF
find ./ -type f |grep -Ev 'pl$|rb$|json$|.htaccess$|.orig$' |while read FILE
do
  echo "Copying ${FILE}" >>$LOG
  install -m 644 "$FILE" "${TARGET}/${FILE}" >>$LOG 2>&1
done
cd ${WORKDIR}/DodontoF
find ./ -type f |grep -E 'pl$|rb$'|grep -v 'src_ruby/config.rb' |while read FILE
do
  echo "Copying ${FILE}" >>$LOG
  install -m 755 "$FILE" "${TARGET}/${FILE}" >>$LOG 2>&1
done
cp ${WORKDIR}/DodontoF/src_ruby/config.rb ${TARGET}/src_ruby/config.rb.newfile

pg_exit ${WORKDIR} 0
