#!/bin/bash

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

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

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

ynh_clean_setup () {
	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="/"
admin=$YNH_APP_ARG_ADMIN
is_public=$YNH_APP_ARG_IS_PUBLIC
classification_color_enabled=$YNH_APP_ARG_CLASSIFICATION_COLOR_ENABLED
classification_location_enabled=$YNH_APP_ARG_CLASSIFICATION_COLOR_ENABLED
classification_style_enabled=$YNH_APP_ARG_CLASSIFICATION_COLOR_ENABLED
classification_object_enabled=$YNH_APP_ARG_CLASSIFICATION_COLOR_ENABLED

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=/opt/yunohost/$app
test ! -e "$final_path" || ynh_die --message="This path already contains a folder"
data_path=/home/yunohost.app/$app
test ! -e "$data_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_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=classification_color_enabled --value=$classification_color_enabled
ynh_app_setting_set --app=$app --key=classification_location_enabled --value=$classification_location_enabled
ynh_app_setting_set --app=$app --key=classification_style_enabled --value=$classification_style_enabled
ynh_app_setting_set --app=$app --key=classification_object_enabled --value=$classification_object_enabled

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# FIND AND OPEN A PORT
#=================================================
ynh_script_progression --message="Finding an available port..." --weight=1

# Find an available port
port=$(ynh_find_port --port=8888)
ynh_app_setting_set --app=$app --key=port --value=$port

#=================================================
# INSTALL DEPENDENCIES
#=================================================
ynh_script_progression --message="Installing dependencies..." --weight=50

ynh_install_app_dependencies $pkg_dependencies
ynh_install_extra_app_dependencies --repo="deb https://dl.yarnpkg.com/debian/ stable main" --package="yarn" --key="https://dl.yarnpkg.com/debian/pubkey.gpg"

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

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

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

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

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

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

set_permissions

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

# Create a dedicated NGINX config
ynh_add_nginx_config data_path

#=================================================
# SPECIFIC SETUP
#=================================================
# YUNOHOST MULTIMEDIA INTEGRATION
#=================================================
ynh_script_progression --message="Adding multimedia directories..." --weight=1

# Build YunoHost multimedia directories
ynh_multimedia_build_main_dir

#=================================================
# PATCH FILES
#=================================================
ynh_script_progression --message="Patching files..." --weight=60

patch_files

#=================================================
# BUILD DJANGO BACKEND
#=================================================
ynh_script_progression --message="Configuring Django backend..." --weight=190

build_django_backend

#=================================================
# BUILD NODE FRONTEND
#=================================================
ynh_script_progression --message="Building Node.js frontend..." --weight=120

build_node_frontend

#=================================================
# ADD A CONFIGURATION
#=================================================

add_envfile

#=================================================
# APPLY DB MIGRATIONS
#=================================================
ynh_script_progression --message="Applying database migrations..." --weight=5

apply_db_migrations

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_script_progression --message="Configuring systemd services..." --weight=5

# Create a dedicated systemd config
add_systemd_configs

#=================================================
# CREATE USERS AND LIBRARIES
#=================================================
ynh_script_progression --message="Creating users and libraries..." --weight=5

admin_mail=$(ynh_user_get_info "$admin" mail)
sudo -u $app bash -c "
	source \"$final_path/venv/bin/activate\"
	set -a
	source \"$final_path/photonix.env\"
	python \"$final_path/photonix/manage.py\" createsuperuser --noinput --username \"$admin\" --email \"$admin_mail\"
"
for username in $(ynh_user_list); do
	user_email=$(ynh_user_get_info --username="$username" --key=mail)
	user_firstname=$(ynh_user_get_info --username="$username" --key=firstname)
	user_lastname=$(ynh_user_get_info --username="$username" --key=lastname)
	sudo -u $app bash -c "
		source \"$final_path/venv/bin/activate\"
		set -a
		source \"$final_path/photonix.env\"
		python \"$final_path/photonix/manage.py\" shell
	" <<< "
from django.contrib.auth import get_user_model
from photonix.photos.models import Library, LibraryUser, LibraryPath
User = get_user_model()
try:
    user = User.objects.get(username='$username')
except User.DoesNotExist:
    user = User.objects.create_user('$username', email='$user_email')

try:
    library_path = LibraryPath.objects.get(path='/home/yunohost.multimedia/$username/Picture')
    library = library_path.library
except LibraryPath.DoesNotExist:
    library = Library(name='$username\'s Personal Library', classification_color_enabled=('$classification_color_enabled' == '1'), classification_location_enabled=('$classification_location_enabled' == '1'), classification_style_enabled=('$classification_style_enabled' == '1'), classification_object_enabled=('$classification_object_enabled' == '1'), setup_stage_completed='Th')
    library.save()
    library_path = LibraryPath(library=library, type='St', backend_type='Lo', path='/home/yunohost.multimedia/$username/Picture', watch_for_changes=True)
    library_path.save()

try:
    library_user = LibraryUser.objects.get(library=library, user=user)
except LibraryUser.DoesNotExist:
    library_user = LibraryUser(library=library, user=user, owner=True)
    library_user.save()

user.firs_tname = '$user_firstname'
user.last_name = '$user_lastname'
user.has_config_persional_info = True
user.has_created_library = True
user.has_configured_importing = True
user.has_configured_image_analysis = True
user.save()

try:
    shared_library_path = LibraryPath.objects.get(path='/home/yunohost.multimedia/share/Picture')
    shared_library = shared_library_path.library
except LibraryPath.DoesNotExist:
    shared_library = Library(name='Shared Library', classification_color_enabled=('$classification_color_enabled' == '1'), classification_location_enabled=('$classification_location_enabled' == '1'), classification_style_enabled=('$classification_style_enabled' == '1'), classification_object_enabled=('$classification_object_enabled' == '1'), setup_stage_completed='Th')
    shared_library.save()
    shared_library_path = LibraryPath(library=shared_library, type='St', backend_type='Lo', path='/home/yunohost.multimedia/share/Picture', watch_for_changes=True)
    shared_library_path.save()

try:
    shared_library_user = LibraryUser.objects.get(library=shared_library, user=user)
except LibraryUser.DoesNotExist:
    shared_library_user = LibraryUser(library=shared_library, user=user, owner=('$username' == '$admin'))
    shared_library_user.save()
"

done

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

# Use logrotate to manage application logfile(s)
set_up_logrotate

#=================================================
# INTEGRATE SERVICES IN YUNOHOST
#=================================================
ynh_script_progression --message="Integrating services in YunoHost..." --weight=1

integrate_services

#=================================================
# START SYSTEMD SERVICES
#=================================================
ynh_script_progression --message="Starting systemd services..." --weight=1

# Start systemd services
start_services

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

# Make app public if necessary
if [ $is_public -eq 1 ]
then
	# Everyone can access the app.
	# The "main" permission is automatically created before the install script.
	ynh_permission_update --permission="main" --add="visitors"
fi

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

ynh_systemd_action --service_name=nginx --action=reload

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

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