#!/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_inst.`date "+%Y%m%d"`.$$
LOG=/tmp/dodontof_inst.`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/\/$//"`

echo "Dodontof install archive is ${ARCHIVE}"
echo "Target directory is ${TARGET}"
echo ""
echo "Is it correct?<y/n>"
read YESNO

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

> ${LOG}

echo "Create ${TARGET} Directory" |tee -a $LOG
if [ ! -d ${TARGET} ]
then
  mkdir ${TARGET}
  chmod 755 ${TARGET}
else
  echo "${TARGET} already exist."
  exit 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 "Copying contents" |tee -a $LOG
cd ${WORKDIR}/DodontoF
cp -av * ${TARGET} >>$LOG 2>&1

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
  cat ${FILE} |sed "1s#.*#\#\!`which ruby` -Ku#" >${TARGET}/${FILE}
  chmod 755 ${TARGET}/${FILE}
done

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

echo "----------------------------" >>$LOG
echo "Changing Permission" |tee -a $LOG
for DIR in "saveData imageUploadSpace imageUploadSpace/smallImages saveDataTempSpace fileUploadSpace replayDataUploadSpace"
do
  echo "Changing permission ${DIR} to 755" >>$LOG
  chmod 755 ${TARGET}/${DIR}
done

find ${TARGET} -type f |grep -Ev 'pl$|rb$'|while read FILE
do
  echo "Changing permission ${FILE} to 644" >>$LOG
  chmod 644 "${FILE}"
done

chmod 666 ${TARGET}/log.txt ${TARGET}/log.txt.0

echo "----------------------------" >>$LOG
echo "Generationg .htaccess" |tee -a $LOG
cat >${TARGET}/.htaccess <<EOF
Options +ExecCGI

AddHandler cgi-script .rb
EOF
chmod 644 ${TARGET}/.htaccess

echo "----------------------------" >>$LOG
echo "Done!!" |tee -a $LOG

pg_exit ${WORKDIR} 0
