#!/bin/bash
# info: Install SnappyMail webmail client
# options: [MODE]
#
# This function installs the SnappyMail webmail client.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Includes
# shellcheck source=/etc/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# load config file
source_conf "$TULIO/conf/tulio.conf"
# upgrade config file
source "$TULIO/install/upgrade/upgrade.conf"

MODE=$1
UPDATE="no"
# Version and Download paths
# Version to be moved to upgrade script
SM_FILE="snappymail-latest.tar.gz"
# For removal of folder
SM_EXTRACT_MAIN="snappymail"

# Downloading full version
SM_URL="https://github.com/the-djmaze/snappymail/releases/download/v${sm_v}/snappymail-${sm_v}.tar.gz"

# Folder paths
SM_INSTALL_DIR="/var/lib/snappymail"
SM_LOG="/var/log/snappymail"

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

# Checking root permissions
if [ "x$(id -u)" != 'x0' ]; then
	echo "ERROR: v-add-sys-snappymail can only be executed by the root user"
	exit 10
fi

# Ensure that $TULIO (/usr/local/tulio/) and other variables are valid.
if [ -z "$TULIO" ]; then
	TULIO="/usr/local/tulio"
fi

if [ -z "$HOMEDIR" ] || [ -z "$TULIO_INSTALL_DIR" ]; then
	echo "ERROR: Environment variables not present, installation aborted."
	exit 2
fi

if [ -z "$(echo "$DB_SYSTEM" | grep -w 'mysql')" ]; then
	echo "ERROR: Mysql not available. Installation aborted"
	exit 2
fi

# Get current version
if [ -f "/var/lib/snappymail/data/VERSION" ]; then
	version=$(cat $SM_INSTALL_DIR/data/VERSION)
	if [ "$version" == "$sm_v" ]; then
		echo "Error: Installed version ($version) is equal to the available version ($sm_v)"
		exit 2
	else
		UPDATE="yes"
	fi
fi

# Perform verification if read-only mode is enabled
check_tulio_demo_mode

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

if [ "$UPDATE" == "no" ]; then
	rm -f -r $SM_INSTALL_DIR

	mkdir $SM_INSTALL_DIR

	cd "$SM_INSTALL_DIR"
	[ ! -f "${SM_INSTALL_DIR}/${SM_FILE}" ] && wget "$SM_URL" --timeout=60 --tries=2 --retry-connrefused --quiet -O "${SM_INSTALL_DIR}/${SM_FILE}"

	if [ ! -f "${SM_INSTALL_DIR}/${SM_FILE}" ]; then
		echo "ERROR: Download failed, installation aborted."
		exit 2
	fi

	key=$(openssl rand -hex 4)
	suffix=$(openssl rand -hex 4)
	admin_account="admin_$key"
	admin_password=$(generate_password)

	echo "Username: admin_$key" > ~/.snappymail
	echo "Password: $admin_password" >> ~/.snappymail
	echo "Admin Panel key: admin_$suffix" >> ~/.snappymail

	tar -xzf ${SM_INSTALL_DIR}/${SM_FILE}
	# Get current version
	version=$(cat ./data/VERSION)

	# Create cache folder and set permissions
	mkdir -p "$SM_INSTALL_DIR/data/_data_/_default_/cache/"
	chown -R www-data:www-data $SM_INSTALL_DIR/data

	if [ -f '/usr/bin/mariadb' ]; then
		mariadb -e "CREATE DATABASE snappymail" 2>&1
		r=$(generate_password)
		mariadb -e "GRANT ALL ON snappymail.*
                 TO snappymail@localhost IDENTIFIED BY '$r'"
	else
		mysql -e "CREATE DATABASE snappymail" 2>&1
		r=$(generate_password)
		mysql -e "GRANT ALL ON snappymail.*
                 TO snappymail@localhost IDENTIFIED BY '$r'"
	fi
	# Temporarily set the permissions to www-data
	chown -R www-data:www-data $SM_INSTALL_DIR/
	php -f $TULIO_COMMON_DIR/snappymail/install.php "admin_$key" "admin_$suffix" "$admin_password" "$r" "$BACKEND_PORT"

	# Set the permissions back to tuliomail
	chown -R tuliomail:www-data $SM_INSTALL_DIR/

	# Remove the downloaded file
	rm ${SM_INSTALL_DIR}/${SM_FILE}
	# Add robots.txt
	echo "User-agent: *" > $SM_INSTALL_DIR/robots.txt
	echo "Disallow: /" >> $SM_INSTALL_DIR/robots.txt

	# Updating tulio.conf
	if [ -z "$(grep WEBMAIL_SYSTEM $TULIO/conf/tulio.conf)" ]; then
		$BIN/v-change-sys-config-value 'WEBMAIL_SYSTEM' 'snappymail'
	else
		if [ -z "$(echo "$WEBMAIL_SYSTEM" | grep -w 'snappymail')" ]; then
			if [ -n "$WEBMAIL_SYSTEM" ]; then
				$BIN/v-change-sys-config-value 'WEBMAIL_SYSTEM' "snappymail,$WEBMAIL_SYSTEM"
			else
				$BIN/v-change-sys-config-value 'WEBMAIL_SYSTEM' "snappymail"
			fi
		fi
	fi

else
	[ ! -f "${SM_INSTALL_DIR}/${SM_FILE}" ] && wget "$SM_URL" --quiet -O "${SM_INSTALL_DIR}/${SM_FILE}"
	if [ ! -f "${SM_INSTALL_DIR}/${SM_FILE}" ]; then
		echo "ERROR: Download failed, installation aborted."
		exit 2
	fi

	version=$(cat $SM_INSTALL_DIR/data/VERSION)
	cd $SM_INSTALL_DIR
	mkdir -p /tmp/snappy/
	tar -xzf snappymail-latest.tar.gz -C /tmp/snappy/
	version_source=$(cat /tmp/snappy/data/VERSION)
	# Check version inside .tar.gz file in case tulio didn't update yet
	if [ "$version" != "$version_source" ]; then
		tar -xzf ${SM_INSTALL_DIR}/${SM_FILE}
		rm $SM_INSTALL_DIR/$SM_FILE
	fi
	rm -fr /tmp/snappy
fi

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

if [ "$UPDATE" = "yes" ]; then
	$BIN/v-log-action "system" "Info" "Plugins" "SnappyMail updated (Version: $version)."
else
	$BIN/v-log-action "system" "Info" "Plugins" "SnappyMail enabled (Version: $version)."
fi
log_event "$OK" "$ARGUMENTS"
