#!/bin/bash

app=$YNH_APP_INSTANCE_NAME

# Source YunoHost helpers
source /usr/share/yunohost/helpers

# Retrieve arguments
domain=$YNH_APP_ARG_DOMAIN
path=$YNH_APP_ARG_PATH
is_public=$YNH_APP_ARG_IS_PUBLIC
port=9001

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

# Store config on YunoHost instance
ynh_app_setting_set "$app" domain "$domain"
ynh_app_setting_set "$app" path "$path"
ynh_app_setting_set "$app" is_public "$is_public"

# Remove trailing "/" for next commands
path=${path%/}

# Generate random key
# key=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d '[A-Za-z0-9]' | sed -n 's/\(.\{40\}\).*/\1/p')
key=$(ynh_string_random 12)

# Generate MySQL password and create database
dbuser=$app
dbname=$app
dbpass=$(ynh_string_random 12)
ynh_mysql_create_db "$dbname" "$dbuser" "$dbpass"
ynh_app_setting_set "$app" dbpass "$dbpass"
ynh_app_setting_set "$app" dbuser "$dbuser"
ynh_app_setting_set "$app" dbname "$dbname"


# Install dependances
if ! ynh_package_is_installed "nodejs-legacy" ; then
  sudo apt-get install nodejs-legacy npm -y
fi

# create app dir and copy sources
final_path=/var/www/$app
sudo mkdir -p $final_path

sudo cp -a ../sources/* $final_path

sudo cp ../conf/settings.json $final_path
# Change variables in etherpad configuration
sudo sed -i "s/yunouser/$dbuser/g" $final_path/settings.json
sudo sed -i "s/yunopass/$dbpass/g" $final_path/settings.json
sudo sed -i "s/yunobase/$dbname/g" $final_path/settings.json
sudo sed -i "s/KEY/$key/g" $final_path/settings.json

sudo npm cache clear
sudo $final_path/bin/installDeps.sh > /dev/null 2>&1
sudo npm install forever -g > /dev/null 2>&1

# Set permissions to etherpad directory
sudo chown -R www-data: $final_path

# service
sudo cp ../conf/etherpad-lite /etc/init.d/$app
sudo sed -i "s/APPTOCHANGE/$app/g" /etc/init.d/$app
sudo chmod +x /etc/init.d/$app
sudo update-rc.d $app defaults

# logs
sudo mkdir /var/log/$app
sudo touch /var/log/$app/$app.log
sudo chown www-data /var/log/$app/$app.log

# nginx
nginx_conf_path=/etc/nginx/conf.d/$domain.d/$app.conf
if [ "$path" = "" ]; then
	sudo cp ../conf/nginx.conf-nosub $nginx_conf_path
else
  sudo cp ../conf/nginx.conf $nginx_conf_path
  # Modify Nginx configuration file and copy it to Nginx conf directory
  sudo sed -i "s@YNH_EXAMPLE_PATH@$path@g" $nginx_conf_path
  sudo sed -i "s@YNH_EXAMPLE_PORT@$port@g" $nginx_conf_path
  sudo sed -i "s@YNH_EXEMPLE_DOMAIN@$domain@g" $nginx_conf_path
fi
# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
# If app is public, add url to SSOWat conf as skipped_uris
if [[ $is_public -eq 1 ]]; then
	# unprotected_uris allows SSO credentials to be passed anyway.
  ynh_app_setting_set "$app" unprotected_uris "/"
fi

sudo yunohost app ssowatconf

sudo service etherpad-lite start
