#!/bin/bash

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

#=================================================
# GENERATE KEYS AND RETRIEVE ADMIN USER INFO
#=================================================

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

email_fullname="$(ynh_user_get_info --username=$admin --key=fullname)"
email="$(ynh_user_get_info --username=$admin --key=mail)"

#=================================================
# STORE KEYS TO APP SETTINGS
#=================================================
ynh_script_progression "Storing secrets to app settings..."

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

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

ynh_setup_source --dest_dir="$install_dir"

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

ynh_config_add_phpfpm

ynh_config_add_nginx

#=================================================
# MODIFY A CONFIG FILE
#=================================================
ynh_script_progression "Updating configuration..."

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

#=================================================
# 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 $email --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"
