#!/bin/bash

set -e

# Retrieve arguments
domain=$(sudo yunohost app setting my_webapp domain)
path=$(sudo yunohost app setting my_webapp path)
user=$(sudo yunohost app setting my_webapp ftp_user \
  || sudo yunohost app setting my_webapp allowed_users \
  || echo "")
is_public=$(sudo yunohost app setting my_webapp is_public)
final_path=/var/www/my_webapp

# Remove trailing "/" from the path
path=${path%/}

# Reset permissions
if [[ "$user" != "" ]]; then
  sudo yunohost app setting my_webapp allowed_users -v "$user"
fi

# Update the salt in the admin.php file
salt=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d 'A-Za-z0-9' | sed -n 's/\(.\{24\}\).*/\1/p')
sed -i "s@SALTTOCHANGE@$salt@g" ../sources/admin.php

# Modify the index.html instruction file
sed -i "s@USER@$user@g" ../sources/files/index.html
sed -i "s@URL@https://$domain$path/admin/@g" ../sources/files/index.html

# Copy files to the right place
sudo mkdir -p $final_path
sudo cp ../sources/admin.php $final_path/
sudo cp -r ../sources/_assets $final_path/

# Set permissions
sudo chmod 775 -R $final_path/files
sudo chown -hR www-data:www-data $final_path/files

# Modify Nginx configuration file and copy it to Nginx conf directory
if [[ "$path" == "" ]]; then
  sed -i "s@LOCATIONTOCHANGE@/@g" ../conf/nginx.conf
else
  sed -i "s@LOCATIONTOCHANGE@$path@g" ../conf/nginx.conf
fi
sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf
sed -i "s@NAMETOCHANGE@my_webapp@g" ../conf/nginx.conf
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/my_webapp.conf

# Same goes for PHP-FPM configuration
sed -i "s@NAMETOCHANGE@my_webapp@g" ../conf/php-fpm.conf
sudo cp ../conf/php-fpm.conf /etc/php5/fpm/pool.d/my_webapp.conf

# Make app public if necessary
if [ "$is_public" = "Yes" ];
then
    sudo yunohost app setting my_webapp unprotected_uris -v "/"
fi

# Protect the file manager
sudo yunohost app setting my_webapp protected_uris -v "/admin"

# Reload Nginx, php5-fpm and regenerate SSOwat conf
sudo service nginx reload
sudo killall php5-fpm || echo "PHP-FPM already killed"
sudo service php5-fpm start
sudo yunohost app ssowatconf
