#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source _common.sh
source /usr/share/yunohost/helpers

#=================================================
# MANAGE SCRIPT FAILURE
#=================================================

ynh_clean_setup () {
	### Remove this function if there's nothing to clean before calling the remove script.
	true
}
# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

#=================================================
# RETRIEVE ARGUMENTS FROM THE MANIFEST
#=================================================

domain=$YNH_APP_ARG_DOMAIN
path_url=$YNH_APP_ARG_PATH
is_public=$YNH_APP_ARG_IS_PUBLIC

app=$YNH_APP_INSTANCE_NAME

#=================================================
# CHECK IF THE APP CAN BE INSTALLED WITH THESE ARGS
#=================================================

### If the app uses nginx as web server (written in HTML/PHP in most cases), the final path should be "/var/www/$app".
### If the app provides an internal web server (or uses another application server such as uwsgi), the final path should be "/opt/yunohost/$app"
final_path=/var/www/$app
test ! -e "$final_path" || ynh_die "This path already contains a folder"

domain_regex=$(echo "$domain" | sed 's@-@.@g')

# Normalize the url path syntax
path_url=$(ynh_normalize_url_path $path_url)

# Check web path availability
ynh_webpath_available $domain $path_url
# Register (book) web path
ynh_webpath_register $app $domain $path_url
CHECK_VAR "$domain_regex" "domain_regex empty"

#=================================================
# FIND AND OPEN A PORT
#=================================================

# Find a free port
port=$(ynh_find_port 8095)
# Open this port
yunohost firewall allow --no-upnp TCP $port 2>&1

#=================================================
# STORE SETTINGS FROM MANIFEST
#=================================================

ynh_app_setting_set $app domain $domain
ynh_app_setting_set $app is_public $is_public
ynh_app_setting_set $app port $port
ynh_app_setting_set $app path $path_url

#=================================================
# INSTALL DEPENDENCIES
#=================================================

ynh_install_app_dependencies build-essential libssl-dev zlib1g-dev libpng-dev libpq-dev memcached postgresql
# Install Carton
echo yes | sudo cpan Carton

#=================================================
# CREATE A POSTGRESQL DATABASE
#=================================================

# Create postgresql database
ynh_psql_test_if_first_run
db_name=$(ynh_sanitize_dbid "$app")
db_user=$db_name
# Initialize database and store postgres password for upgrade
ynh_psql_setup_db "$db_name" "$db_user"
ynh_app_setting_set "$app" db_name "$db_name"
db_pwd=$(ynh_app_setting_get $app psqlpwd) # Password created in ynh_psql_setup_db function

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

ynh_app_setting_set $app final_path $final_path
# Download, check integrity, uncompress and patch the source from app.src
ynh_setup_source "$final_path"

#=================================================
# NGINX CONFIGURATION
#=================================================

### `ynh_add_nginx_config` will use the file conf/nginx.conf

# Create a dedicated nginx config
ynh_add_nginx_config

#=================================================
# CREATE DEDICATED USER
#=================================================

# Create a system user
ynh_system_user_create $app

#=================================================
## Copy and fix variable into lstu config
#=================================================

cp ../conf/lstu.conf.template "${final_path}/lstu.conf"
ynh_replace_string "__DOMAIN__" "$domain" "${final_path}/lstu.conf"
ynh_replace_string "__PATH__" "$path_url" "${final_path}/lstu.conf"
ynh_replace_string "__PORT__" "$port" "${final_path}/lstu.conf"
ynh_replace_string "__DB_NAME__" "$db_name"  "${final_path}/lstu.conf"
ynh_replace_string "__DB_USER__" "$db_user"  "${final_path}/lstu.conf"
ynh_replace_string "__DB_PWD__" "$db_pwd" "${final_path}/lstu.conf"

secret=$(ynh_string_random 24)
ynh_replace_string "__SECRET__" "$secret" "${final_path}/lstu.conf"
ynh_store_file_checksum "${final_path}/lstu.conf"

#=================================================
# SETUP SYSTEMD
#=================================================

# Create a dedicated systemd config
ynh_add_systemd_config

#=================================================
# Install lstu's dependencies via carton
#=================================================

pushd $final_path
carton install --deployment --without=sqlite --without=mysql
popd

#=================================================
# SETUP LOGROTATE
#=================================================

# Use logrotate to manage application logfile(s)
ynh_use_logrotate

#=================================================
# ADVERTISE SERVICE IN ADMIN PANEL
#=================================================

yunohost service add $app --log "/var/log/$app.log"

#=================================================
# SETUP SSOWAT
#=================================================

# Make app public or private
ynh_app_setting_set $app skipped_uris "/"
if [ $is_public -eq 0 ];
then	# If the app is private, only the shortened URLs are publics
	if [ "$path_url" == "/" ]; then
		path_url=""
	fi
	ynh_app_setting_set $app protected_regex "$domain_regex$path_url/login$","$domain_regex$path_url/logout$","$domain_regex$path_url/api$","$domain_regex$path_url/extensions$","$domain_regex$path_url/stats$","$domain_regex$path_url/d/.*$","$domain_regex$path_url/a$","$domain_regex$path_url/$"
else
	ynh_replace_string "#--PRIVATE--" "" "/etc/nginx/conf.d/$domain.d/$app.conf"
fi

#=================================================
# Configure owner
#=================================================

sudo chown -R www-data $final_path

#=================================================
# Start lstu
#=================================================

systemctl enable lstu.service
systemctl start lstu

#=================================================
# RELOAD NGINX
#=================================================

# Reload Nginx
sudo service nginx reload