#!/bin/bash

# Retrieve arguments
domain=$(sudo yunohost app setting owncloud domain)
path=$(sudo yunohost app setting owncloud path)
#user=$(sudo yunohost app setting owncloud admin_user)
db_pwd=$(sudo yunohost app setting owncloud mysqlpwd)

# Install dependencies
#sudo apt-get install acl smbclient -y -qq

# Remove trailing "/" for next commands
path=${path%/}

# Use 'owncloud' as database name and user
db_user=owncloud

# Copy files to the right place
final_path=/var/www/owncloud
data_path=/home/yunohost.app/owncloud/data
sudo mkdir -p $final_path
sudo mkdir -p $data_path
sudo cp -a ../sources/* $final_path
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/owncloud.conf
sudo cp ../conf/php-fpm.conf /etc/php5/fpm/pool.d/owncloud.conf
sudo cp ../conf/mount.json $data_path
sudo chown -hR owncloud:www-data $final_path
sudo chown -hR owncloud:www-data $data_path
sudo chmod 755 /home/yunohost.app
sudo chmod 664 -R $final_path
sudo find $final_path -type d -print0 | xargs -0 sudo chmod 775
sudo chmod -R 770 $data_path

# Change variables in Owncloud configuration
sudo sed -i "s@PATHTOCHANGE@$path@g" /etc/nginx/conf.d/$domain.d/owncloud.conf
sudo sed -i "s@ALIASTOCHANGE@$final_path/@g" /etc/nginx/conf.d/$domain.d/owncloud.conf
sudo sed -i "s@NAMETOCHANGE@owncloud@g" /etc/nginx/conf.d/$domain.d/owncloud.conf
sudo sed -i "s@NAMETOCHANGE@owncloud@g" /etc/php5/fpm/pool.d/owncloud.conf

# Reload Nginx and regenerate SSOwat conf
sudo service php5-fpm restart
sudo service nginx reload
sudo yunohost app setting owncloud unprotected_uris -v "/"
sudo yunohost app setting owncloud skipped_uris -d
sudo yunohost app ssowatconf

# Optionnal DB upgrade here

# Configure LDAP plugin
mysql -u $db_user -p$db_pwd $db_user < ../conf/ldap_config.sql

sudo chown -hR owncloud:owncloud $final_path
sudo chown -hR owncloud:owncloud $data_path
sudo chmod 755 /home/yunohost.app
sudo chmod -R 770 $data_path
sudo chmod -R 775 $final_path

# Unprotect URIs
sudo yunohost app ssowatconf
