#!/bin/sh

X_DEBIAN_SITEID=default

# pass a siteid on cli if you want (todo: loop through all args)
if [ -n "$1" ]
then
	X_DEBIAN_SITEID=${1}
fi

# these are the debian redmine package locations
export X_DEBIAN_SITEID
export RAILS_ETC=/etc/redmine/${X_DEBIAN_SITEID}
export RAILS_LOG=/var/log/redmine/${X_DEBIAN_SITEID}
export RAILS_VAR=/var/lib/redmine/${X_DEBIAN_SITEID}
export RAILS_CACHE=/var/cache/redmine/${X_DEBIAN_SITEID}
export RAILS_ENV=production
RAKEFILE=/usr/share/redmine/Rakefile

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

if [ ! -d $RAILS_ETC ]
then
	mkdir $RAILS_ETC
	chown www-data:www-data $RAILS_ETC
  chmod 755 $RAILS_ETC
fi
if [ ! -d $RAILS_LOG ]
then
	mkdir $RAILS_LOG
	chown www-data:www-data $RAILS_LOG
  chmod 750 $RAILS_LOG
fi
if [ ! -d $RAILS_VAR ]
then
	mkdir -p $RAILS_VAR/files
	chown -R www-data:www-data $RAILS_VAR
  chmod 750 $RAILS_VAR
  chmod 755 $RAILS_VAR/files
fi
if [ ! -d $RAILS_VAR ]
then
	mkdir $RAILS_CACHE
	chown www-data:www-data $RAILS_CACHE
  chmod 750 $RAILS_CACHE
fi
  
if [ ! -f $RAILS_ETC/database.yml ]
then
	cp /usr/share/redmine/templates/database.yml.template $RAILS_ETC/database.yml
	chown root:www-data $RAILS_ETC/database.yml
	chmod 640 $RAILS_ETC/database.yml

	echo "Error: Database config for X_DEBIAN_SITEID ${X_DEBIAN_SITEID} not found, creating from template." 1>&2
	echo "Error: You need to edit $RAILS_ETC/database.yml then continue" 1>&2
	exit 1
fi

if [ -f $RAILS_ETC/email.yml ]
then
	chown root:www-data $RAILS_ETC/email.yml
	chmod 640 $RAILS_ETC/email.yml
fi

if [ ! -f ${RAKEFILE} ]
then
	echo "Error: rakefile [${RAKEFILE}] does not exist, can't continue." 1>&2
	exit 1
fi

rake -f ${RAKEFILE} generate_session_store

if [ -f $RAILS_ETC/email.yml ]
then
	chown root:www-data $RAILS_ETC/session.yml
	chmod 640 $RAILS_ETC/session.yml
fi

ruby /usr/share/redmine/script/about
exit

rake -f ${RAKEFILE} db:migrate --trace
rake -f ${RAKEFILE} redmine:load_default_data
rake -f ${RAKEFILE} db:migrate:upgrade_plugin_migrations
rake -f ${RAKEFILE} db:migrate_plugins

rake -f ${RAKEFILE} tmp:cache:clear
rake -f ${RAKEFILE} tmp:sessions:clear

