#!/bin/bash

set -e

# Source app helpers
. /usr/share/yunohost/helpers

# Set app specific variables
app="agendav"
dbname=$app
dbuser=$app

# Retrieve arguments
domain=$(ynh_app_setting_get "$app" domain)
path=$(ynh_app_setting_get "$app" path)
path=${path%/}
dbpass=$(ynh_app_setting_get "$app" mysqlpwd)
encryptkey=$(ynh_app_setting_get "$app" encryptkey)

# Check destination directory
DESTDIR="/var/www/$app"
[[ ! -d $DESTDIR ]] && ynh_die \
"The destination directory '$DESTDIR' does not exist.\
 The app is not correctly installed, you should remove it first."

# Check whether Baïkal or Radicale is installed
if sudo yunohost app list --installed -f baikal | grep -q id ; then
    caldav_app="baikal"
    caldav_principal_path="/cal.php/%u/"
    caldav_calendar_path="/cal.php/calendars/%s/"
elif sudo yunohost app list --installed -f radicale | grep -q id ; then
    caldav_app="radicale"
    caldav_principal_path="/%u/"
    caldav_calendar_path="/%s/"
else
    ynh_die "You must install Baïkal or Radicale before"
fi

# Install dependencies
ynh_package_is_installed "php5-cli" \
  || ynh_package_install "php5-cli"

# Clean up existing files and copy new files to the right place
sudo rm -rf "$DESTDIR"
sudo cp -r ../sources "$DESTDIR"

# CalDAV config
caldav_domain=$(ynh_app_setting_get "$caldav_app" domain)
caldav_path=$(ynh_app_setting_get "$caldav_app" path)
caldav_url="https://${caldav_domain}${caldav_path%/}"
sed -i "s@{PRINCIPAL_URL}@${caldav_url}${caldav_principal_path}@g" \
    ../conf/caldav.php
sed -i "s@{CALENDAR_URL}@${caldav_url}${caldav_calendar_path}@g" \
    ../conf/caldav.php

# Database config
sed -i "s/{DBUSER}/${dbuser}/g" ../conf/database.php
sed -i "s/{DBPASS}/${dbpass}/g" ../conf/database.php
sed -i "s/{DBNAME}/${dbname}/g" ../conf/database.php

# Main config
LOGDIR=/var/log/agendav
lang=${LANG/.*/}
sed -i "s@{DOMAIN}@${domain}@g" ../conf/config.php
sed -i "s@{PATH}@${path}@g" ../conf/config.php
sed -i "s@{LOGDIR}@${LOGDIR}@g" ../conf/config.php
sed -i "s/{ENCRYPTKEY}/${encryptkey}/g" ../conf/config.php
sed -i "s@{COOKIE_PREFIX}@${path#/}@g" ../conf/config.php
sed -i "s@{COOKIE_DOMAIN}@${domain}@g" ../conf/config.php
sed -i "s@{LANG}@${lang:-en_EN}@g" ../conf/config.php
sed -i "s@{TIMEZONE}@$(cat /etc/timezone)@g" ../conf/config.php

# Copy config files and set permissions
sudo cp ../conf/{config,database,caldav}.php "${DESTDIR}/web/config/"
(cd "$DESTDIR/web/application" && sudo ln -s ../config config)
sudo chown -hR root: "$DESTDIR"

# Create log directory
sudo install -m 750 -o www-data -d "$LOGDIR"

# Execute database shema update
sudo /var/www/agendav/bin/agendavcli dbupdate

# Copy and set nginx configuration
nginx_conf="/etc/nginx/conf.d/${domain}.d/${app}.conf"
sed -i "s@{LOCATION}@${path:-/}@g" ../conf/nginx.conf
sed -i "s@{DESTDIR}@${DESTDIR}@g"  ../conf/nginx.conf
sudo cp ../conf/nginx.conf "$nginx_conf"

# Reload services
sudo service nginx reload || true
