#!/bin/bash

set -e
app=kanboard

# Retrieve arguments
domain=$1
path=$2
admin=$3
is_public=$4

# Retrieve admin email
email=$(sudo yunohost user info $admin | grep mail: | sed "s/mail: //g")

# Check domain/path availability
sudo yunohost app checkurl $domain$path -a $app  \
    || (echo "Path not available: $domain$path" && exit 1)

# Generate random password
db_pwd=$(openssl rand -hex 15)

# Initialize database and store mysql password for upgrade
sudo yunohost app initdb $app -p $db_pwd
sudo yunohost app setting $app mysqlpwd -v $db_pwd
sudo yunohost app setting $app adminusername -v $admin
sudo yunohost app setting $app is_public -v $is_public

# Copy sources
final_path=/var/www/$app
sudo mkdir -p $final_path
sudo cp -a ../sources/. $final_path

# Copy and edit config.php
sudo cp ../conf/config.php $final_path
sudo sed -i "s/yuno_dbpdw/$db_pwd/g" $final_path/config.php
sudo sed -i "s/yuno_dbuser/$app/g" $final_path/config.php
sudo sed -i "s/yuno_admin/$admin/g" $final_path/config.php
sudo sed -i "s/yuno_email/$email/g" $final_path/config.php
sudo sed -i "s/yuno_domain/$domain/g" $final_path/config.php

# Set permissions to kanboard and data directory
sudo chown -R root:root $final_path
sudo chown -R www-data:www-data $final_path/data

# Use dedicated php pool
sed -i "s@NAMETOCHANGE@$app@g" ../conf/php-fpm.conf
finalphpconf=/etc/php5/fpm/pool.d/$app.conf
sudo cp ../conf/php-fpm.conf $finalphpconf
sudo chown root: $finalphpconf
sudo chmod 644 $finalphpconf

# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@NAMETOCHANGE@$app@g" ../conf/nginx.conf*
sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf*
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf*
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf

# Make app public or private
if [ "$is_public" = "Yes" ];
then
	sudo yunohost app setting $app unprotected_uris -v "/"
	sudo sed -i "s/define('LDAP_AUTH'.*$/define('LDAP_AUTH', true);/g" $final_path/config.php
	sudo sed -i "s/define('HIDE_LOGIN_FORM'.*$/define('HIDE_LOGIN_FORM', false);/g" $final_path/config.php
	sudo sed -i "s/define('REMEMBER_ME_AUTH'.*$/define('REMEMBER_ME_AUTH', true);/g" $final_path/config.php
	sudo sed -i "s/define('DISABLE_LOGOUT'.*$/define('DISABLE_LOGOUT', false);/g" $final_path/config.php
fi

# Reload Nginx, PHP5-FPM and regenerate SSOwat conf
sudo service php5-fpm restart
sudo service nginx reload
sudo yunohost app ssowatconf
