#!/bin/bash

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

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

mail=$(ynh_user_get_info --username=$admin --key=mail)

#=================================================
# INITIALIZE AND STORE SETTINGS
#=================================================

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_script_progression "Setting up source files..."

ynh_setup_source --dest_dir="$install_dir"

chown -R "$app:www-data" "$install_dir"

pushd $install_dir
 ynh_exec_as_app python3 -m venv venv
 echo "source $install_dir/venv/bin/activate" >> $install_dir/.bashrc
 source "$install_dir/venv/bin/activate"
 ynh_exec_as_app pip install open-webui
 ynh_exec_as_app open-webui serve
 deactivate
popd

chown -R "$app:www-data" "$install_dir"

#=================================================
# APP INITIAL CONFIGURATION
#=================================================
ynh_script_progression "Adding $app's configuration files..."

ynh_config_add --template=".env" --destination="$install_dir/.env"

chmod 400 "$install_dir/.env"
chown "$app:$app" "$install_dir/.env"

#=================================================
# SYSTEM CONFIGURATION
#=================================================
ynh_script_progression "Adding system configurations related to $app..."

ynh_config_add_nginx

ynh_config_add_logrotate

#ynh_config_add_fail2ban --logpath="/var/log/nginx/${domain}-error.log" --failregex="Regex to match into the log for a failed login"

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

ynh_script_progression "Installation of $app completed"
