#!/bin/bash

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

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

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

ynh_clean_setup () {
	ynh_clean_check_starting
}
# 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="/"
is_public=$YNH_APP_ARG_IS_PUBLIC
admin=$YNH_APP_ARG_ADMIN

app=$YNH_APP_INSTANCE_NAME

#=================================================
# CHECK IF THE APP CAN BE INSTALLED WITH THESE ARGS
#=================================================
ynh_print_info --message="Validating installation parameters..."

final_path="/var/www/$app"
test ! -e "$final_path" || ynh_die --message="This path already contains a folder"

# Register (book) web path
ynh_webpath_register --app="$app" --domain="$domain" --path_url="$path_url"

#=================================================
# STORE SETTINGS FROM MANIFEST
#=================================================
ynh_print_info --message="Storing installation settings..."

ynh_app_setting_set --app="$app" --key=domain --value="$domain"
ynh_app_setting_set --app="$app" --key=path --value="$path_url"
ynh_app_setting_set --app="$app" --key=is_public --value="$is_public"
ynh_app_setting_set --app="$app" --key=admin --value="$admin"

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# FIND AND OPEN A PORT
#=================================================
ynh_print_info --message="Configuring firewall..."

# Find a free port
port=$(ynh_find_port --port=5000)
# Open this port
ynh_app_setting_set --app="$app" --key=port --value="$port"

#=================================================
# INSTALL DEPENDENCIES
#=================================================
ynh_print_info --message="Installing dependencies..."

ynh_install_app_dependencies $pkg_dependencies

#=================================================
# CREATE A POSTGRESQL DATABASE
#=================================================
ynh_print_info --message="Creating a PostgreSQL database..."

ynh_psql_test_if_first_run

db_name=$(ynh_sanitize_dbid "$app")
db_user="$db_name"
db_pwd=$(ynh_string_random)
ynh_app_setting_set --app="$app" --key=db_name --value="$db_name"
ynh_app_setting_set --app="$app" --key=psqlpwd --value="$db_pwd"

# Initialize database and store postgres password for upgrade
ynh_psql_setup_db --db_name="$db_name" --db_user="$db_user" --db_pwd="$db_pwd"

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_print_info --message="Setting up source files..."

ynh_app_setting_set --app="$app" --key=final_path --value="$final_path"
# Download, check integrity, uncompress and patch the source from app.src
ynh_setup_source --dest_dir="$final_path/code"
ynh_setup_source --dest_dir="$final_path/code" --source_id="app-frontend"

(
	cd "$final_path"
	mkdir -p code/config code/api code/data/static media import code/front
)

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_print_info --message="Configuring nginx web server..."

# Create a dedicated nginx config
ynh_add_nginx_config

#=================================================
# CREATE DEDICATED USER
#=================================================
ynh_print_info --message="Configuring system user..."

# Create a system user
ynh_system_user_create --username="$app" --home_dir="$final_path"

#=================================================
# SPECIFIC SETUP
#=================================================
# PYTHON DEPENDENCIES
#=================================================

virtualenv -p python3 "$final_path/code/virtualenv"
(
	set +o nounset
	source "${final_path}/code/virtualenv/bin/activate"
	set -o nounset
	pip install --upgrade pip
	pip install --upgrade setuptools
	pip install wheel
	pip install -r "${final_path}/code/api/requirements.txt"
)

#=================================================
# MODIFY THE CONFIG FILE
#=================================================

configfile="$final_path/code/config/.env"

cp ../conf/env.prod "$configfile"

key=$(ynh_string_random)
redis_db=$(ynh_redis_get_free_db)

ynh_app_setting_set --app="$app" --key=key --value="$key"
ynh_app_setting_set --app="$app" --key=redis_db --value="$redis_db"

ynh_replace_string --match_string="__REDIS_DB__"  --replace_string="$redis_db"    --target_file="$configfile"
ynh_replace_string --match_string="__PORT__"      --replace_string="$port"        --target_file="$configfile"
ynh_replace_string --match_string="__DOMAIN__"    --replace_string="$domain"      --target_file="$configfile"
ynh_replace_string --match_string="__DBUSER__"    --replace_string="$db_name"     --target_file="$configfile"
ynh_replace_string --match_string="__DBPWD__"     --replace_string="$db_pwd"      --target_file="$configfile"
ynh_replace_string --match_string="__DBNAME__"    --replace_string="$app"         --target_file="$configfile"
ynh_replace_string --match_string="__FINALPATH__" --replace_string="$final_path"  --target_file="$configfile"
ynh_replace_string --match_string="__KEY__"       --replace_string="$key"         --target_file="$configfile"

#=================================================
# CONFIGURE ADMIN USER
#=================================================

admin_mail=$(ynh_user_get_info --username="$admin" --key="mail")
(
	set +o nounset
	source "${final_path}/code/virtualenv/bin/activate"
	set -o nounset
	cd "$final_path/code/"

	# needed for enabling the 'unaccent' extension
	ynh_psql_execute_as_root --sql="ALTER USER $db_user WITH SUPERUSER;" --database="$db_name"
	python api/manage.py migrate
	ynh_psql_execute_as_root --sql="ALTER USER $db_user WITH NOSUPERUSER;" --database="$db_name"
	echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('$admin', '$admin_mail', 'funkwhale') " | python api/manage.py shell
	python api/manage.py collectstatic
)

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_print_info --message="Configuring a systemd service..."

cp ../conf/funkwhale.target "/etc/systemd/system/$app.target"
ynh_replace_string --match_string="__APP__"    --replace_string="$app"   --target_file="/etc/systemd/system/$app.target"

# Create a dedicated systemd config
ynh_add_systemd_config --service="$app-server" --template="funkwhale-server.service"
ynh_add_systemd_config --service="$app-worker" --template="funkwhale-worker.service"
ynh_add_systemd_config --service="$app-beat"   --template="funkwhale-beat.service"

#=================================================
# STORE THE CONFIG FILE CHECKSUM
#=================================================

# Calculate and store the config file checksum into the app settings
ynh_store_file_checksum --file="$configfile"

#=================================================
# GENERIC FINALIZATION
#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================

chown -R "$app": "$final_path"
chmod -R 755 "$final_path/code/front/dist/"

mkdir -p "/var/log/$app"
chown -R "$app": "/var/log/$app"

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

yunohost service add "$app-server" --log="/var/log/$app/server.log"
yunohost service add "$app-worker" --log="/var/log/$app/worker.log"
yunohost service add "$app-beat"   --log="/var/log/$app/beat.log"

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_print_info --message="Starting a systemd service..."

ynh_systemd_action --action="start" --service_name="${app}-beat"
ynh_systemd_action --action="start" --service_name="${app}-server"
ynh_systemd_action --action="start" --service_name="${app}-worker"

#=================================================
# SETUP FAIL2BAN
#=================================================
ynh_print_info --message="Configuring fail2ban..."

# Create a dedicated fail2ban config
ynh_add_fail2ban_config --logpath="/var/log/nginx/$domain-access.log" --failregex="<HOST>.* \"POST /api/v1/token/ HTTP/1.1\" 400 68.*$" --max_retry=5

#=================================================
# SETUP SSOWAT
#=================================================
ynh_print_info --message="Configuring SSOwat..."

# Make app public if necessary
if [ "$is_public" -eq 1 ]
then
	# makes sure no SSO credentials to be passed
	ynh_app_setting_set --app="$app" --key=skipped_uris --value="/"
fi

#=================================================
# RELOAD NGINX
#=================================================
ynh_print_info --message="Reloading nginx web server..."

ynh_systemd_action --service_name=nginx --action=reload

#=================================================
# END OF SCRIPT
#=================================================

ynh_print_info --message="Installation of $app completed"