#!/bin/bash

# Retrieve arguments
domain=$1
path=$2
language=$3
public_site=$4

# Check domain/path availability
sudo yunohost app checkurl $domain$path -a movim
if [[ ! $? -eq 0 ]]; then
exit 1
fi

#sudo yunohost app setting movim language -v $language
#sudo yunohost app setting movim public_site -v $public_site

# Generate random password
db_pwd=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d '[A-Za-z0-9]' | sed -n 's/\(.\{24\}\).*/\1/p')

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

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

# Prereqs
sudo apt-get install php5-gd php5-curl php5-imagick -y

# Copy files to the right place
final_path=/var/www/movim
sudo mkdir -p $final_path
sudo cp -a ../sources/* $final_path

# Set permissions to Movim directory
sudo chown -R www-data: $final_path

# Install PHP dependencies
cd $final_path
curl -sS https://getcomposer.org/installer | php
php composer.phar install

# Movim configuration
mv $final_path/config/db.example.inc.php $final_path/config/db.inc.php
sed -i "s/yhuser/$db_user/g" $final_path/config/db.inc.php
sed -i "s/yhpwd/$db_pwd/g" $final_path/config/db.inc.php
sed -i "s/yhdb/$db_user/g" $final_path/config/db.inc.php

# Prepare database
su -c "php mud.php db set" -s /bin/sh www-data
#sudo yunohost app addaccess opensondage -u $admin #a voir

# Copy init script if Wheezy
cp -a ../conf/movim.init /etc/init.d/movim
sed -i "s/YHDIR/$final_path/g" /etc/init.d/movim

# Copy systemd service if Jessie
# todo

# Nginx configuration
sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf
cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/movim.conf

# Start Movim
/etc/init.d/movim start

# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
sudo yunohost app setting opensondage skipped_uris -v "/"  
if [ $public_site = "No" ];
then              
	sudo yunohost app setting opensondage protected_uris -v "/admin,/index.php,/choix_date.php,/choix_autre.php,/infos_sondage.php,/scripts" 
else              
	sudo yunohost app setting opensondage protected_uris -v "/admin/index.php,/admin/logs_studs.txt,/scripts"
fi
sudo yunohost app ssowatconf
