#!/bin/bash

# Retrieve arguments
backup_dir=$1
app=${!#}

# TODO: Put a simple die function in app helpers, redeclare it since
# _common.sh cannot be easily sourced
die() {
  printf "%s" "$1" 1>&2
  exit "${2:-1}"
}

# Set app specific variables
dbname=$app
dbuser=$app

# Source app helpers
. /usr/share/yunohost/helpers

# Retrieve old app settings
domain=$(ynh_app_setting_get $app domain)
path=$(ynh_app_setting_get $app path)
dbpass=$(ynh_app_setting_get $app mysqlpwd)

# TODO: Check domain/path availability with app helper
sudo yunohost app checkurl $domain$path -a $app \
  || die "The path ${domain}${path} is not available for app installation."

# Check destination directory
DESTDIR="/var/www/$app"
[[ -d $DESTDIR ]] && die \
"The destination directory '$DESTDIR' already exists.\
 You should safely delete it before restoring this app."

# Define app's data directory
DATADIR="/home/yunohost.app/${app}/data"

# Check configuration files
nginx_conf="/etc/nginx/conf.d/${domain}.d/${app}.conf"
[[ -f $nginx_conf ]] && die \
"The NGINX configuration already exists at '${nginx_conf}'.
 You should safely delete it before restoring this app."
phpfpm_conf="/etc/php5/fpm/pool.d/${app}.conf"
[[ -f $phpfpm_conf ]] && die \
"The PHP FPM configuration already exists at '${phpfpm_conf}'.
 You should safely delete it before restoring this app."

# Install dependencies
ynh_package_install_from_equivs ./owncloud-deps.control \
  || die "Unable to install dependencies"

# Create a system account for ownCloud
sudo useradd -c "$app system account" \
    -d /var/lib/$app --system --user-group $app \
  || die "Unable to create $app system account"

# Restore the app files
sudo cp -a ./www "$DESTDIR"
sudo mkdir -p "$DATADIR"
sudo cp -a ./data/. "$DATADIR"

# Create and restore the database
ynh_mysql_create_db $dbname $dbuser $dbpass
ynh_mysql_connect_as $dbuser $dbpass $dbname < ./db.sql

# Iterate over users to extend their home folder permissions - for the external
# storage plugin usage - and create relevant ownCloud directories
for u in $(ynh_user_list); do
  sudo mkdir -p "${DATADIR}/${u}"
  sudo setfacl -m g:$app:rwx "/home/$u" || true
done

# Fix app ownerships & permissions
sudo chown -R $app: "$DESTDIR" "$DATADIR"
sudo find ${DESTDIR}/ -type f -print0 | sudo xargs -0 chmod 0644
sudo find ${DESTDIR}/ -type d -print0 | sudo xargs -0 chmod 0755
sudo find ${DATADIR}/ -type f -print0 | sudo xargs -0 chmod 0640
sudo find ${DATADIR}/ -type d -print0 | sudo xargs -0 chmod 0750
sudo chmod 640 "${DESTDIR}/config/config.php"
sudo chmod 755 /home/yunohost.app

# Restore configuration files
sudo cp -a ./conf/nginx.conf   "$nginx_conf"
sudo cp -a ./conf/php-fpm.conf "$phpfpm_conf"

# Reload services
sudo service php5-fpm restart || true
sudo service nginx reload || true