#!/bin/bash

source /usr/share/yunohost/helpers

ynh_abort_if_errors

# RETRIEVE ARGUMENTS
app=$YNH_APP_INSTANCE_NAME

ynh_script_progression --message="Installing zola project : $app"

domain=$YNH_APP_ARG_DOMAIN
path_url=$YNH_APP_ARG_PATH
is_public=$YNH_APP_ARG_IS_PUBLIC
git_url=$YNH_APP_ARG_PROJECT_URL


# PRE-INSTALLATION CHECKS

ynh_script_progression --message="Doing some checks"

path_url=$(ynh_normalize_url_path $path_url)

final_path=/var/www/$app
test ! -e "$final_path" || ynh_die "This path already contains a folder"

ynh_webpath_available $domain $path_url
ynh_webpath_register $app $domain $path_url

# STORE SETTINGS

ynh_script_progression --message="Going through with installation"

ynh_app_setting_set $app domain $domain
ynh_app_setting_set $app path $path_url
ynh_app_setting_set $app final_path $final_path
ynh_app_setting_set $app is_public $is_public
ynh_app_setting_set $app git_url $git_url

# SETUP SSOWAT

if [ $is_public -eq 1 ]; then
	ynh_permission_update --permission "main" --add visitors
fi

# BUILD PROJECT

ynh_script_progression --message="Build zola project"

(
	tmp_dir=/tmp/$app
	mkdir $tmp_dir && cd $tmp_dir
	git clone $git_url source
	cd source/
	zola build --base-url $path_url --output-dir $final_path
	rm -r $tmp_dir
)

chmod 755 -R $final_path

# CONFIGURE NGINX

ynh_script_progression --message="Configure nginx"
ynh_add_nginx_config






