#!/bin/bash

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

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

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

# 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
admin=$YNH_APP_ARG_ADMIN
password=$YNH_APP_ARG_PASSWORD
is_public=$YNH_APP_ARG_IS_PUBLIC
github_account=$YNH_APP_ARG_GITHUB_ACCOUNT
github_token=$YNH_APP_ARG_GITHUB_TOKEN

app=$YNH_APP_INSTANCE_NAME

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

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

mkdir -p "$final_path"

#=================================================
# STORE SETTINGS FROM MANIFEST
#=================================================
ynh_script_progression --message="Storing installation settings..." --weight=1

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=admin --value="$admin"
ynh_app_setting_set --app="$app" --key=final_path --value="$final_path"
ynh_app_setting_set --app="$app" --key=github_account --value="$github_account"
ynh_app_setting_set --app="$app" --key=github_token --value="$github_token"

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# INSTALL DEPENDENCIES
#=================================================
ynh_script_progression --message="Installing dependencies..." --weight=40

ynh_exec_warn_less ynh_install_app_dependencies "$pkg_dependencies"

#=================================================
# CREATE A PostgreSQL DATABASE
#=================================================
ynh_script_progression --message="Creating a PostgreSQL database..." --weight=2

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

ynh_psql_test_if_first_run

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

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_script_progression --message="Configuring NGINX web server..." --weight=2

# Create a dedicated nginx config
ynh_add_nginx_config

#=================================================
# CREATE DEDICATED USER
#=================================================
ynh_script_progression --message="Configuring system user..." --weight=1

# Hub needs a home directory with a config file
ynh_system_user_create --username="$app" --home_dir="$final_path" --use_shell

#=================================================
# CONFIGURE HUB
#=================================================
ynh_script_progression --message="Configure hub..." --weight=1

mkdir "$final_path/.config/"
ynh_add_config --template="../conf/hub_config" --destination="$final_path/.config/hub"

cat <<EOF > "$final_path/.bashrc"
eval "$(hub alias -s /bin/bash)"
EOF

#=================================================
# SPECIFIC SETUP
#=================================================
# PIP INSTALLATION
#=================================================
ynh_script_progression --message="Install weblate using PIP..." --weight=80

ynh_psql_execute_as_root --sql="CREATE EXTENSION IF NOT EXISTS pg_trgm;" --database=$db_name

virtualenv --python=python3 "${final_path}/venv"
chown -R "$app": "$final_path"

#run source in a 'sub shell'
(
	set +o nounset
	source "${final_path}/venv/bin/activate"
	set -o nounset
	cd "${final_path}"

	sudo --user=$app $final_path/venv/bin/pip install --upgrade pip setuptools wheel
	# Tmp fix
	sudo --user=$app $final_path/venv/bin/pip install --upgrade cffi==1.14
	# Still needed with latest version of weblate?
	sudo --user=$app $final_path/venv/bin/pip install Weblate=="$weblate_version"
	sudo --user=$app $final_path/venv/bin/pip install psycopg2-binary ruamel.yaml aeidon phply
	#pip install pytz python-bidi PyYaML Babel pyuca pylibravatar py3dns psycopg2-binary phply django-redis hiredis aeidon ruamel.yaml
	# specific to YunoHost package:
	sudo --user=$app $final_path/venv/bin/pip install django_sendmail_backend
)

#=================================================
# SPECIFIC SETUP settings.py
# https://docs.weblate.org/en/latest/admin/install.html#installation
# TODO: use --extra-search-dir=/path/to/dists
#=================================================
ynh_script_progression --message="Create weblate configuration file..." --weight=1

db_pwd=$(ynh_app_setting_get --app="$app" --key=psqlpwd)
admin_mail=$(ynh_user_get_info --username="$admin" --key=mail)
key=$(ynh_string_random --length=50)
redis_db=$(ynh_redis_get_free_db)
path_url="${path_url%/}"
settings="$final_path/venv/lib/$weblate_pypath/site-packages/weblate/settings.py"

ynh_add_config --template="../conf/settings.py" --destination="$settings"

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

touch "$final_path/local_settings.py"
ln -sf "$final_path/local_settings.py" "$final_path/venv/lib/$weblate_pypath/site-packages/weblate/local_settings.py"

#=================================================
# SPECIFIC SETUP Filling up the database
# https://docs.weblate.org/en/latest/admin/install.html#filling-up-the-database
#==========================================
ynh_script_progression --message="Filling up the database..." --weight=10

(
	set +o nounset
	source "${final_path}/venv/bin/activate"
	set -o nounset
	export DJANGO_SETTINGS_MODULE="weblate.settings"
	cd "${final_path}"

	# the user needs to be weblate for postgresql
	sudo --user=$app $final_path/venv/bin/weblate migrate --noinput
	# generate static files
	sudo --user=$app $final_path/venv/bin/weblate collectstatic --noinput
	sudo --user=$app $final_path/venv/bin/weblate createadmin --no-color \
		--password "$password" \
		--username "$admin" \
		--email "$admin_mail"

	# Check the configuration
	# This may fail in some cases with errors, etc., but the app works and the user can fix issues later.
	sudo --user=$app $final_path/venv/bin/weblate check --deploy || true
)

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

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

#=================================================
# SPECIFIC SETUP UWSGI
#=================================================
ynh_script_progression --message="Configure uwsgi..." --weight=1

finaluwsgiini="/etc/uwsgi/apps-available/$app.ini"

ynh_add_config --template="../conf/uwsgi.ini" --destination="$finaluwsgiini"

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_script_progression --message="Configuring a systemd service..." --weight=2

ynh_add_systemd_config --service="$app" --template="weblate.service"

#=================================================
# ACTIVATE CELERY
#=================================================
ynh_script_progression --message="Configure celery..." --weight=1

celeryconf="$final_path/celery-weblate"

ynh_add_config --template="../conf/celery-weblate" --destination="$celeryconf"

ynh_add_systemd_config --service="$app-celery" --template="celery-weblate.service"

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

# Set permissions to app files
mkdir -p "$final_path/avatar-cache"
chown -R "$app": "$final_path"
chown "$app:www-data" "$final_path"
chown -R "$app:www-data" "$final_path/data"

chmod 750 "$final_path"
chmod -R o-rwx "$final_path"

#=================================================
# SETUP LOGROTATE
#=================================================
ynh_script_progression --message="Configuring log rotation..." --weight=1

# Use logrotate to manage application logfile(s)
ynh_use_logrotate --non-append

#=================================================
# INTEGRATE SERVICE IN YUNOHOST
#=================================================
ynh_script_progression --message="Integrating service in YunoHost..." --weight=3

yunohost service add "$app" --log "/var/log/$app/weblate.log"
yunohost service add "$app-celery" --log "/var/log/$app/weblate-celery-w1.log"

#=================================================
# SETUP SSOWAT
#=================================================
ynh_script_progression --message="Configuring permissions..." --weight=1

# Make app public if necessary
if [ "$is_public" -eq 1 ]
then
	ynh_permission_update --permission="main" --add="visitors"
fi

#=================================================
# Start weblate
#=================================================
ynh_script_progression --message="Starting weblate's services..." --weight=5

ynh_systemd_action --service_name="$app" --action="start"
ynh_systemd_action --service_name="$app-celery" --action="start"

#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression --message="Reloading NGINX web server..." --weight=1

ynh_systemd_action --service_name="nginx" --action="reload"

#=================================================
# SEND A README FOR THE ADMIN
#=================================================

message="
Weblate settings file          : $settings
If you facing an issue or want to improve this app, please open a new issue in this project: https://github.com/YunoHost-Apps/weblate_ynh
"

ynh_send_readme_to_admin "$message" "$admin"

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

ynh_script_progression --message="Installation of $app completed" --last