#!/bin/bash

# Exit on command errors and treat unset variables as an error
set -eu

app=$YNH_APP_INSTANCE_NAME

# Source YunoHost helpers
source /usr/share/yunohost/helpers
source ./_common.sh

# Get app settings
admin=$(ynh_app_setting_get "$app" admin)
is_public=$(ynh_app_setting_get "$app" is_public)
language=$(ynh_app_setting_get "$app" language)
domain=$(ynh_app_setting_get "$app" domain)
path_url=$(ynh_app_setting_get "$app" path)

# Copy source files
final_path=/var/www/$app

### MySQL (can be removed if not used) ###
# If your app use a MySQL database you can use these lines to bootstrap
# a database, an associated user and save the password in app settings.
#
# # Generate MySQL password and create database
dbuser=$app
dbname=$app
dbpass=$(ynh_app_setting_get "$app" mysqlpwd)

extract_monica $final_path
#ynh_setup_source $final_path

# install new dependencies
ynh_package_install g++ php7.0-curl

# create a user
first_name=$(ynh_user_get_info $admin 'firstname')
last_name=$(ynh_user_get_info $admin 'lastname')
email=$(ynh_user_get_info $admin 'mail')

sudo sed -i "s/yuno_firstname/$first_name/g"  ../conf/CreateUser.php
sudo sed -i "s/yuno_lastname/$last_name/g" ../conf/CreateUser.php
sudo sed -i "s/yuno_email/$email/g" ../conf/CreateUser.php
sudo  cp ../conf/CreateUser.php $final_path/database/seeds/CreateUser.php

# setup application config
sudo cp ../conf/.env $final_path/.env

sudo sed -i "s/yunouser/$dbuser/g" $final_path/.env
sudo sed -i "s/yunopass/$dbpass/g" $final_path/.env
sudo sed -i "s/yunobase/$dbname/g" $final_path/.env
sudo sed -i "s/yunomail/$email/g" $final_path/.env
sudo sed -i "s/yunodomain/$domain/g" $final_path/.env
# uses commas because path url contains a slash
sudo sed -i "s,yunopath,${path_url},g" $final_path/.env

# setup application config
cd $final_path && sudo /usr/bin/php7.0 artisan migrate --force
cd $final_path && sudo /usr/bin/php7.0 artisan optimize

# Install files and set permissions
sudo chown -R www-data: "$final_path"

# If app is public, add url to SSOWat conf as skipped_uris
if [[ $is_public -eq 1 ]]; then
  # unprotected_uris allows SSO credentials to be passed anyway.
  ynh_app_setting_set "$app" unprotected_uris "/"
fi
