#!/bin/bash

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

app=$YNH_APP_INSTANCE_NAME
version='1.1.0'

# Retrieve arguments
	domain=$YNH_APP_ARG_DOMAIN
	path=$YNH_APP_ARG_PATH

# Source YunoHost helpers
	source /usr/share/yunohost/helpers

# Save app settings
	ynh_app_setting_set "$app" admin "$admin"
	ynh_app_setting_set "$app" is_public "$is_public"
	ynh_app_setting_set "$app" language "$language"

# Check domain/path availability
	sudo yunohost app checkurl "${domain}${path}" -a "$app" \
		|| ynh_die "Path not available: ${domain}${path}"

# Copy source files
	src_path=/var/www/$app
	sudo mkdir -p $src_path
	sudo unzip -qq ../sources/humhub-$version.zip
	sudo cp -a humhub-$version/. $src_path

# MySQL
	dbuser=$app
	dbname=$app
	dbpass=$(ynh_string_random 12)
	ynh_app_setting_set "$app" mysqlpwd "$dbpass"
	ynh_mysql_create_db "$dbname" "$dbuser" "$dbpass"
	
# Conf
	app_conf=../conf/common.php
	sed -i "s@DBNAME_TO_CHANGE@$dbname@g" $app_conf
	sed -i "s@DBUSER_TO_CHANGE@$dbuser@g" $app_conf
	sed -i "s@DBPASS_TO_CHANGE@$dbpass@g" $app_conf
	sudo cp $app_conf $src_path/protected/config/common.php

# Set permissions to app files
	sudo chown -R root: $src_path
	
# Cron
	echo "30 * * * * $src_path/public_html/yiic cron hourly >/dev/null 2>&1" > cron
	echo "00 18 * * * $src_path/public_html/yiic cron daily >/dev/null 2>&1" > cron
	sudo mv cron /etc/cron.d/${app}
	sudo chown root /etc/cron.d/${app}

# Modify Nginx configuration file and copy it to Nginx conf directory
	nginx_conf=../conf/nginx.conf
	sed -i "s@YNH_WWW_PATH@$path@g" $nginx_conf
	sed -i "s@YNH_WWW_ALIAS@$src_path/@g" $nginx_conf
	sudo cp $nginx_conf /etc/nginx/conf.d/$domain.d/$app.conf

# Reload services
	sudo service nginx reload
