#!/bin/bash

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

source /usr/share/yunohost/helpers

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

api_secret="$(ynh_string_random --length=32)"
app_key="$(ynh_string_random --length=32)"
phantomjs_key="$(ynh_string_random --length=32)"

mail_address=$(ynh_app_setting_get --key=mail_address)
mail_name=$(ynh_app_setting_get --key=mail_name)

ynh_app_setting_set --key=api_secret --value=$api_secret
ynh_app_setting_set --key=app_key --value=$app_key
ynh_app_setting_set --key=phantomjs_key --value=$phantomjs_key
#ynh_app_setting_set --key=mail_address --value="$mail_address"
#ynh_app_setting_set --key=mail_name --value="$mail_name"

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

# Download, check integrity, uncompress and patch the source from manifest.toml
ynh_setup_source --dest_dir="$install_dir"

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

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

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

# Create a PHP-FPM config (with conf/extra_php-fpm.conf being appended to it)
ynh_config_add_phpfpm

# Create a dedicated NGINX config using the conf/nginx.conf template
ynh_config_add_nginx

#=================================================
# BUILD THE APPLICATION
#=================================================
ynh_script_progression "Building the application..."

pushd "$install_dir"
	# Run the database migrations and initially fill the db
	php$php_version artisan migrate:fresh --seed --no-interaction --verbose --force
	php$php_version artisan ninja:create-account --email $mail_address --password "$password" --no-interaction --verbose
	php$php_version artisan optimize --no-interaction --verbose
	php$php_version artisan view:clear
	php$php_version artisan cache:clear
popd

# invoiceninja creates some directories that need to be chmod'ed
chmod 750 "$install_dir"
chmod -R o-rwx "$install_dir"
chown -R $app:www-data "$install_dir"

#=================================================
# ADD A CRON JOB
#=================================================
ynh_script_progression "Adding a cron job..."

ynh_config_add --template="cron" --destination="/etc/cron.d/$app"

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

ynh_script_progression "Installation of $app completed"
