#!/bin/bash

app=lutim

# Retrieve arguments
domain=$(sudo yunohost app setting $app domain)
path=$(sudo yunohost app setting $app path)
is_public=$(sudo yunohost app setting $app is_public)
port=$(sudo yunohost app setting $app port)
always_encrypt=$(sudo yunohost app setting $app always_encrypt)

# Vérifie l'absence du / en fin de path
pathRslash=$(echo "$path" | sed 's@/$@@')
# Modifie le domaine pour qu'il passe dans une regex
domain_regex=$(echo "$domain" | sed 's@-@.@g')

# Copy files to right place
final_path=/var/www/$app
# Décompresse la source
tar -x -f ../sources/lutim.tar.gz
sudo cp -a lutim/. "$final_path"
sudo cp -a ../sources/ajouts/. "$final_path"
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf

# Change variables in nginx configuration
sudo sed -i "s@__PATH__@$path@g" /etc/nginx/conf.d/$domain.d/$app.conf
sudo sed -i "s@__PORT__@$port@g" /etc/nginx/conf.d/$domain.d/$app.conf

## Copie et configuration du fichier de conf.
sudo cp ../conf/lutim.conf.template "$final_path/lutim.conf"
sudo sed -i "s@__DOMAIN__@$domain@g" "$final_path/lutim.conf"
sudo sed -i "s@__PATH__@$path@g" "$final_path/lutim.conf"
sudo sed -i "s@__PORT__@$port@g" "$final_path/lutim.conf"
if [ "always_encrypt" = "No" ]; then
	always_encrypt=0
else
	always_encrypt=1
fi
sudo sed -i "s@__ENCRYPT__@$always_encrypt@g" "$final_path/lutim.conf"

# Mise en place des scripts init
sudo cp ../conf/lutim.init /etc/init.d/lutim
sudo sed -i "s@__FINALPATH__@$final_path@g" /etc/init.d/lutim
sudo cp ../conf/lutim.default /etc/default/lutim
sudo chmod +x /etc/init.d/lutim
sudo chown root:root /etc/init.d/lutim /etc/default/lutim
sudo sed -i "s@__FINALPATH__@$final_path/@g" /etc/default/lutim

## Mise en place des crons
sudo cp ../conf/cron_lutim /etc/cron.d/$app
sudo sed -i "s@__FINALPATH__@$final_path/@g" /etc/cron.d/$app

# Mise à jour de lutim via carton
cd $final_path
sudo carton install 2>&1 | sudo tee -a "/var/log/$app/setup_carton.log"

# Make app public or private
sudo yunohost app setting $app skipped_uris -v "/"
if [ "$is_public" = "No" ];
then	# Si l'app est privée, seul le visionnage des images reste public
	sudo yunohost app setting $app protected_regex -v "$domain_regex$pathRslash/stats$","$domain_regex$pathRslash/manifest.webapp$","$domain_regex$pathRslash/$","$domain_regex$pathRslash/d/.*$","$domain_regex$pathRslash/m/.*$"
fi

# Set right permissions
sudo chown -R www-data: $final_path
# Restart lutim
sudo /etc/init.d/lutim restart


# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
sudo yunohost app ssowatconf
