set -e

# Retrieve arguments
domain=$1
path=$2

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

path=${path%/}

sudo apt-get install postgresql php5 php5-pgsql php5-gd php-gettext p7zip-full libgd2-xpm-dev -y

final_path=/var/www/noalyss
sudo mkdir -p $final_path
sudo cp -a ../sources/html/ $final_path
sudo cp -a ../sources/include/ $final_path

sudo chown -R www-data: $final_path

sudo yunohost app setting noalyss version -v "6.9.0.0"

if [[ "$path" == "" ]]; then
  sed -i "s@PATHTOCHANGE@/@g" ../conf/nginx.conf
else
  sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf
fi

sed -i "s@ALIASTOCHANGE@$final_path/html/@g" ../conf/nginx.conf

sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/noalyss.conf

sed -i "s@NAMETOCHANGE@noalyss@g" ../conf/php-fpm.conf

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')

sudo su postgres -c "createuser -S -R --createdb noalyss"
sudo su postgres -c "psql -c \"ALTER USER noalyss with PASSWORD '$db_pwd';\""

sed -i "s@DATABASE_PASSWORD@$db_pwd@g" ../conf/noalyss.conf
sudo cp ../conf/noalyss.conf $final_path/include/config.inc.php

finalphpconf=/etc/php5/fpm/pool.d/noalyss.conf

sudo cp ../conf/php-fpm.conf $finalphpconf
sudo chown root: $finalphpconf
sudo chmod 644 $finalphpconf

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

sudo yunohost app setting noalyss unprotected_uris -v ""
sudo yunohost app ssowatconf
curl -kL -H "Host: $domain" -X POST https://127.0.0.1$path/admin/setup.php --data "go=yolo" > /dev/null 2>&1
sudo yunohost app setting noalyss unprotected_uris -v ""
sudo yunohost app ssowatconf

# su postgres -c "psql account_repository -c 'delete from ac_users;'"
