#! /bin/bash

# causes the shell to exit if any subcommand or pipeline returns a non-zero status
set -e
# causes the shell to exit if you try to use an uninitialised variable
set -u

ynh_version=$(sudo yunohost -v | grep "moulinette:" | cut -d' ' -f2 | cut -d'.' -f1,2)

#retrieve arguments
if [ $ynh_version = "2.4" ]; then
	app=$YNH_APP_INSTANCE_NAME
else
	app=bozon
fi
save_path=$1
domain=$(sudo yunohost app setting $app domain)

# definie useful vars
app=bozon
parent_path=/var/www
final_path=$parent_path/$app
data_path=/home/yunohost.app/$app

# restore sources & data
sudo mv $save_path/www/. $final_path/
sudo mv $save_path/datas/. $data_path/

# restore permissions
sudo chown -R root: $final_path
sudo find $final_path -type f | xargs sudo chmod 644
sudo find $final_path -type d | xargs sudo chmod 755
sudo chown -R www-data: $final_path/private
sudo chown -R www-data: $data_path/uploads
sudo chown -R www-data: $data_path/thumbs

# restore php-fpm, Nginx and YunoHost parameters
sudo cp -a $save_path/yunohost/. /etc/yunohost/apps/$app/
sudo cp -a $save_path/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf
sudo cp -a $save_path/php-fpm.conf /etc/php5/fpm/pool.d/$app.conf

# Restart services
sudo service php5-fpm restart || true
sudo service nginx restart || true
sudo yunohost app ssowatconf