#!/bin/bash

# Define constants
DB_VLW="vlw"
DB_API="vlw_api"

# Initialize variables
cwd=""
database_app_host=""
database_app_user=""
database_seed_host=""
database_seed_user=""
database_app_password=""
database_seed_password=""

echo_err() {
	echo "!! -> $1"
}

# Make sure we have all the system packages we need to proceed with the installation
check_sys_depend() {
	local valid=true
	local packages=("git" "composer")

	for package in "${packages[@]}" ; do
		if ! dpkg -l | grep -qw "ii  ${package}" ; then
			echo_err "Package '${package}' is not installed."
			valid=false
		fi
	done

	# Bail out if any required package is missing
	if [ "$valid" = false ] ; then
		exit 1
	fi
}

install_vegvisir() {
	echo
	echo "Installing Vegvisir into '$cwd/vegvisir'"

	curl -fsSL https://codeberg.org/vegvisir/install/raw/branch/master/install.sh | bash -s -- --install=n --overwrite=y --example=n --dir="$cwd"
}

install_reflect() {
	echo
	echo "Installing Reflect into '$cwd/reflect'"

	curl -fsSL https://codeberg.org/reflect/install/raw/branch/master/install.sh | bash -s -- --install=n --overwrite=y --seed=n --dir="$cwd" --endpoints="api" --host="$database_app_host" --user="$database_app_user" --password="$database_app_password" --db="$DB_API"
}

install_vlw() {
	composer install --classmap-authoritative
}

seed_databases() {
	echo
	echo "-- Database seeding --"
	echo "We're now going to seed the databases '$DB_VLW' and '$DB_API' with default data"
	echo "- Make sure that both databases exist and are empty"
	echo "- Your credentials for this user '$(whoami)' might be different from your app credentials (php-mysql)"
	echo

	# Database seed hostname
	echo "Enter the full hostname of your MySQL/MariaDB server to use in this script for seeding."
	read -p "Press enter to use the same host as the app credentials [$database_app_host]: " database_seed_host </dev/tty

	# Use the same database host as the app configuration
	if [[ "$database_seed_host" == "" ]] ; then
		database_seed_host=$database_app_host
	fi

	# Database seed user
	echo
	echo "Enter the username for your MySQL/MariaDB server to use in this script for seeding."
	read -p "Press enter to use the same host as the app credentials [$database_app_user]: " database_seed_user </dev/tty

	# Use the same database user as the app configuration
	if [[ "$database_seed_user" == "" ]] ; then
		database_seed_user=$database_app_user
	fi

	# Database seed password
	echo
	echo "Enter the password for your MySQL/MariaDB server to use in this script for seeding."
	echo "Enter 'null' to disable password authentication"
	read -p "Press enter to use the same password as the app credentials [<database_password>]: " database_seed_password </dev/tty

	# Use the same database password as the app configuration
	if [[ "$database_seed_password" == "" ]] ; then
		database_seed_password=$database_app_password
	fi

	# Seed the main database
	mysql -h "$database_seed_host" -u "$database_seed_user" --password="$database_seed_password" $DB_VLW < src/Database/Seeds/vlw.sql # Structure
	mysql -h "$database_seed_host" -u "$database_seed_user" --password="$database_seed_password" $DB_VLW < src/Database/Seeds/data/vlw.sql # Data

	# Seed the API database
	mysql -h "$database_seed_host" -u "$database_seed_user" --password="$database_seed_password" $DB_API < src/Database/Seeds/api.sql # Structure
	mysql -h "$database_seed_host" -u "$database_seed_user" --password="$database_seed_password" $DB_API < src/Database/Seeds/data/vlw_reflect.sql # Data
}

configure_vlw() {
	local config_password=""

	local config_available=""
	local config_available_to=""
	local config_available_from=""
	local config_available_average=""
	local config_available_timezone=""

	local config_forgejo=""
	local config_forgejo_url=""
	local config_forgejo_profiles=""

	# A configuration file already exists
	if [[ -f ".env.ini" ]] ; then
		echo
		echo "A configuration file already exists at: ${cwd}/.env.ini"
		read -p "Do you want to overwrite this file? (y/n): " overwrite </dev/tty

		# Remove existing configuration file or abort
		if [[ "$overwrite" == "y" || "$overwrite" == "Y" ]] ; then
			echo "Removing existing configuration and proceeding with the installation in ${cwd}..."
			rm .env.ini
		else
			echo_err "Installation aborted: Configuration file already exists"
			exit 1
		fi
	fi

	echo
	echo "-- Database configuration --"
	read -p "Enter the full hostname of your MySQL/MariaDB server (php-mysql): " database_app_host </dev/tty
	read -p "Enter the app username for your MySQL/MariaDB server (php-mysql): " database_app_user </dev/tty
	read -p "Enter the app password for your MySQL/MariaDB server (php-mysql): " config_password </dev/tty

	# Coerce empty input as null keyword for later configurations
	if [[ "$config_password" == "" ]] ; then
		database_app_password="null"
	fi

	echo
	read -p "(Optional) Would you like to configure time available settings? (y/n): " config_available </dev/tty

	# Check the user's response
	if [[ "$config_available" == "n" || "$config_available" == "N" ]]; then
		config_available_to=0
		config_available_from=0
		config_available_average=0
		config_available_timezone="Europe/Stockholm"
	fi

	if ! [[ -n "$config_available_timezone" ]]; then
		read -p "Enter your timezone in IANA Time Zone Database Format ('Europe/Stockholm' for example): " config_available_timezone </dev/tty
	fi

	if ! [[ -n "$config_available_from" ]]; then
		read -p "Enter time available from hour (24-hour format): " config_available_from </dev/tty
	fi

	if ! [[ -n "$config_available_to" ]]; then
		read -p "Enter time available to hour (24-hour format): " config_available_to </dev/tty
	fi

	if ! [[ -n "$config_available_average" ]]; then
		read -p "Enter average reply time in hours: " config_available_average </dev/tty
	fi

	echo
	read -p "(Optional) Would you like to configure Forgejo language updates? (y/n): " config_forgejo </dev/tty

	# Check the user's response
	if [[ "$config_forgejo" == "n" || "$config_forgejo" == "N" ]]; then
		config_forgejo_url="https://git.vlw.se"
		config_forgejo_profiles="vlw,vegvisir,reflect"
	fi

	if ! [[ -n "$config_forgejo_url" ]]; then
		read -p "Enter a hostname to a Forgejo instance ('https://git.vlw.se' for example): " config_forgejo_url </dev/tty
	fi

	if ! [[ -n "$config_forgejo_profiles" ]]; then
		read -p "Enter a comma seperated list of Forgejo profiles to scan ('vlw,vegvisir,reflect' for example): " config_forgejo_profiles </dev/tty
	fi

	local config=(
		"; This config file was generated automatically by ./install.sh"
		"; Refer to '.env.example.ini' for more information"
		"[mariadb]"
		"host = '$database_app_host'"
		"user = '$database_app_user'"
		"pass = '$config_password'"
		"db = '$DB_VLW'"
		"[config_time_available]"
		"time_zone = '$config_available_timezone'"
		"available_to_hour = '$config_available_to'"
		"reply_average_hours = '$config_available_average'"
		"available_from_hour = '$config_available_from'"
		"[service_forgejo]"
		"url = '$config_forgejo_url'"
		"profiles = '$config_forgejo_profiles'"
	)

	for line in "${config[@]}" ; do
		echo "${line}" >> .env.ini
	done
}

main() {
	# Get the current working directory
	cwd=$(pwd)

	check_sys_depend

	configure_vlw
	seed_databases

	install_vlw
	install_vegvisir
	install_reflect

	echo "-- Success --"
	echo "vlw.se has been installed! :)"
	echo "- Point all traffic to your web server to '${cwd}/vegvisir/public/index.php'"
	echo "- Point all traffic to your REST API server to '${cwd}/reflect/public/index.php'"
	echo "-------------"
	echo
}

# Prompt the user for confirmation
echo
echo "-- Installing vlw.se --"
echo "You are currently in: $(pwd)"
read -p "Do you want to proceed with the installation in this directory? (y/n): " choice </dev/tty

# Check the user's response
if [[ "$choice" == "y" || "$choice" == "Y" ]] ; then
	echo "Proceeding with the installation in $(pwd)..."
	main
else
	echo "Installation aborted."
fi
