#!/bin/bash

OWNCLOUDPATH=/var/www/owncloud
INSTALLED_FILENAME=${OWNCLOUDPATH}/installed

if [ -e "${INSTALLED_FILENAME}" ]; then
  exit 0
fi

APT_REPO_PREFIX="http://download.opensuse.org/repositories/isv:ownCloud:community"

DATADIR=/data

OS_VERSION=$(lsb_release -sr)
OS_ID=$(lsb_release -si)

# tools for owncloud
apt-get -y install php-apc curl libapache2-mod-php5

# install mySQL (set root user password to root)
echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5 unzip

if grep -q inet /etc/group; then
    usermod -a -G inet mysql
fi

mysql -uroot -proot <<EOFMYSQL
CREATE USER 'owncloud'@'localhost' IDENTIFIED BY 'owncloud';
CREATE DATABASE IF NOT EXISTS owncloud;
GRANT ALL PRIVILEGES ON owncloud.* TO 'owncloud'@'localhost' IDENTIFIED BY 'owncloud';
EOFMYSQL

if [[ ${OS_ID} = "Debian" ]]; then
    OWNCLOUD_REPO=${APT_REPO_PREFIX}/Debian_7.0
else
    OWNCLOUD_REPO=${APT_REPO_PREFIX}/xUbuntu_${OS_VERSION}
fi

wget --no-check-certificate -qO - ${OWNCLOUD_REPO}/Release.key | apt-key add -
echo "deb ${OWNCLOUD_REPO}/ /" > /etc/apt/sources.list.d/owncloud.list

cat <<APTPREF > /etc/apt/preferences
Package: *
Pin: origin download.opensuse.org
Pin-Priority: 610
APTPREF

apt-get update
apt-get -y --no-install-recommends install owncloud

if grep -q inet /etc/group; then
    # add www-data user to inet group
    usermod -a -G inet www-data
fi

echo "owncloud dir:"
ls -la ${OWNCLOUDPATH}

echo "owncloud apps"
ls -la ${OWNCLOUDPATH}/apps/

# disable some owncloud apps
sed -i -e "/<default_enable\/>/d" ${OWNCLOUDPATH}/apps/contacts/appinfo/info.xml
sed -i -e "/<default_enable\/>/d" ${OWNCLOUDPATH}/apps/calendar/appinfo/info.xml
sed -i -e "/<default_enable\/>/d" ${OWNCLOUDPATH}/apps/updater/appinfo/info.xml


# Apache configuration
if [[ ${OS_ID} = "Ubuntu" ]]; then

cat <<APACHE > /etc/apache2/sites-available/owncloud.conf
<Directory /var/www/owncloud>
  AllowOverride All
</Directory>
APACHE

  # apache 2.2 fix
  ln -s /etc/apache2/sites-available/owncloud.conf /etc/apache2/sites-available/owncloud

  echo "apache sites available:"
  ls -la /etc/apache2/sites-available/
  echo "apache sites enabled:"
  ls -la /etc/apache2/sites-enabled/

fi

if [[ ${OS_ID} = "Debian" ]]; then
  echo "Alias /owncloud ${OWNCLOUDPATH}" > /etc/apache2/sites-available/owncloud.conf
fi

a2ensite owncloud

dpkg -l | grep apache
service apache2 status
service apache2 restart

echo "apache error log:"
tail -100 /var/log/apache2/error.log

echo "apache default page:"
curl localhost

# setup crontab task
su -c "echo \"*/1 * * * * php -f ${OWNCLOUDPATH}/cron.php\" | crontab -" www-data

echo "Installed successfully" > ${INSTALLED_FILENAME}

#hiding real exit code as restart is not fully working in chroot
exit 0