# Accept the first parameter as a number of the command to skip to.
# Useful for restarting an interuppted install.
SKIP_TO_CMD="${1:-1}" # Uses $1 if not blank, otherwise defaults to 1

CMD_COUNT=1
# Fancy script output, allows command editing in-flight
function cmd_exec () {
	if [[ $CMD_COUNT -ge $SKIP_TO_CMD ]]; then
		echo
		# Display the command description in blue, and the editable
		#	command in cyan. Remove the colors before executing.
		read -e \
			-p $'\033[0;34m'"[#${CMD_COUNT}] ${1}: "$'\033[0;32m'$'\n'"$(whoami)@$(hostname)"$'\033[0m'":"$'\033[0;36m'"$(pwd)"$'\033[0m'"$ " \
			-i "${2}" \
			CMD
		# Execute the command
		eval "$CMD"
		#read -p $'\n'"Press [enter] to continue..."
	else
		echo -e "\033[0;34mSkipping command ${CMD_COUNT}"$'\n'"${1}\033[0m"$'\n'
	fi
	((CMD_COUNT++))
}

function config_suggestions () {
	# This function will show the current setting, ask for user input (using the suggestion as a basis)
	#	and replace the existing line with the user input. By default, uncomments the setting, but
	#	user can comment it out by prepending a comment character (usually ; or #)

	# Adding line below because my sudo kept timing out,
	#	and didn't want to recommend NOPASSWD -AES
	sudo echo "Sudo access confirmed..."
	CONFIG_PATH="$(echo "$1"	| sed -n '1p')" # /var/www/mbin/.env
	SETTING_FORMAT="$(echo "$1"	| sed -n '2p')" # %setting% = %var%
	COMMENT_CHAR="$(echo "$1"	| sed -n '3p')" # (#|;|//)
	CONFIG_SUGGESTIONS="$(echo "$1"	| sed '1,3d')"

	IFS=$'\n'
	for SETTING_SUGGESTION in $(echo "${CONFIG_SUGGESTIONS}"); do
		SETTING_NAME="$(echo ${SETTING_SUGGESTION} | awk '{print $1}')"
		SETTING_SUG_VAL="$(echo ${SETTING_SUGGESTION} | awk '{print $2}')"
		echo
		# Set the string that defines the suggested configuration line
		SETTING_LINE="$(echo "${SETTING_FORMAT}" | sed "s|%name%|${SETTING_NAME}|" | sed "s|%value%|${SETTING_SUG_VAL}|")"
		# Get the line number of the last occurance of the command
		LAST_LINE=$(sudo sed -n -r "/^[ $(printf '\t')${COMMENT_CHAR}]*${SETTING_NAME}[= $(printf '\t')]+.*$/ =" $CONFIG_PATH | tail -n1)
		# Show the current value (last line that starts with the setting's name
		if [[ "${LAST_LINE}" = "" ]]; then
			echo       "  Current value: Not found. User input will be appended to the file.";

		else
			echo -n    "  Current value: "; sudo cat ${CONFIG_PATH} | grep -P "^[	 ${COMMENT_CHAR}]*${SETTING_NAME}[= $(printf '\t')]+" | tail -n1
		fi
		# Display the complete line of setting suggestion for this setting, formatted by SETTING_FORMAT
		read -e -p "Suggested value: " -i "${SETTING_LINE}" SETTING_INPUT
		#	(preceded by any combination/number of whitespace and the comment character)
		if [[ "${LAST_LINE}" = "" ]]; then
			# Append the line to the end of the file
			sudo bash -c "echo \"${SETTING_INPUT}\" >> $CONFIG_PATH"
		else
			# Replace the setting by name/line number
			sudo sed -i -r "${LAST_LINE} s|^[ $(printf '\t')${COMMENT_CHAR}]*${SETTING_NAME}[= $(printf '\t')]+.*$|${SETTING_INPUT}|" $CONFIG_PATH
		fi
		# Show the content of the file after the modification, just the last occurance of the setting by name (as above)
		echo -n	   "   Stored value: "; sudo cat ${CONFIG_PATH} | grep -P "^[	 ${COMMENT_CHAR}]*${SETTING_NAME}[= $(printf '\t')]+" | tail -n1
	done
}

##
# User sanity check and creation instructions if needed
##

if [[ ! "$(whoami)" == "mbin" ]]; then
	echo -e '\033[0;34m'
	echo "This script should be run as a user named 'mbin'."
	echo "Switch to that user and execute this script again."
	echo "If the user doesn't exist yet, create it;"
	echo -e '\033[0;36m'
	echo 'sudo adduser mbin'
	echo 'sudo usermod -aG sudo mbin'
	echo 'sudo usermod -aG www-data mbin'
	echo 'sudo su - mbin'
	echo -e '\033[0m'
	exit 1
fi

##
# Command tests
##

# Commands need to end in ; and
#	the line needs to be ended in \ in order
#	to have multi-line commands
#cmd_exec "Set and use a variable" \
#'TEST="Some Text"; \
#echo "$TEST"'

#cmd_exec "Use the variable later" \
#'echo "$TEST"'

#cmd_exec "Change dir" \
#"cd /var/www/mbin"

#cmd_exec "List dir" \
#"ls -lah"

#cmd_exec "Generalized config suggestion test refresh" \
#'cp /home/mbin/test.php.ini_reset /home/mbin/test.php.ini'
#
#PHP_SUGGESTIONS='/home/mbin/test.php.ini
#%name% = %value%
##
#setting_one 99
#setting_two 45K
#setting_three trewf
#setting_four something
#setting_five mbin.something.net
#setting_six non-false
#'
#
#cmd_exec "Generalized config suggestion test" \
#'config_suggestions "$PHP_SUGGESTIONS"'

##
# System Prerequisites
##

cmd_exec "System Prerequisites - Bring system up to date" \
"sudo apt-get update && sudo apt-get upgrade -y"

cmd_exec "System Prerequisites - Install prequirements" \
"sudo apt-get install lsb-release ca-certificates curl wget unzip gnupg apt-transport-https software-properties-common python3-launchpadlib git redis-server postgresql postgresql-contrib nginx acl -y"

# This is optional, but it doesn't hurt anything, and covers all cases. -AES
cmd_exec "System Prerequisites - Prepare latest PHP package repositoy" \
"sudo add-apt-repository ppa:ondrej/php -y; sudo apt-get update"

cmd_exec "System Prerequisites - Install PHP 8.2 with some important PHP extensions" \
"sudo apt-get install php8.2 php8.2-common php8.2-fpm php8.2-cli php8.2-amqp php8.2-pgsql php8.2-gd php8.2-curl php8.2-xml php8.2-redis php8.2-mbstring php8.2-zip php8.2-bz2 php8.2-intl php8.2-bcmath -y"

cmd_exec "System Prerequisites - Install Composer (pt 1)" \
"sudo curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php"

cmd_exec "System Prerequisites - Install Composer (pt 2)" \
"sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer"

##
# Firewall
##

# The following note should be added somewhere, but it doesn't describe an action that happens on the server. -AES
# If you have a firewall installed (or you're behind a NAT), be sure to open port 443 for the web server.
# Mbin should run behind a reverse proxy like Nginx.

##
# Install NodeJS (frontend tools)
##

cmd_exec "Install NodeJS (frontend tools) - Prepare & download keyring" \
"sudo mkdir -p /etc/apt/keyrings; curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg"

cmd_exec "Install NodeJS (frontend tools) - Setup deb repository" \
'NODE_MAJOR=20; echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list'

cmd_exec "Install NodeJS (frontend tools) - Update apt and install NodeJS" \
"sudo apt-get update; sudo apt-get install nodejs -y"

# This is where the new user instructions show up in the guide, but we've already covered that in the sanity check -AES

##
# Create folder
##

cmd_exec "Create folder" \
"sudo mkdir -p /var/www/mbin; sudo chown mbin:www-data /var/www/mbin"

##
# Generate Secrets
##

cmd_exec "Generate Secrets
Note: This will generate several valid tokens for the Mbin setup, you will need quite a few." \
"for counter in {1..2}; do node -e \"console.log(require('crypto').randomBytes(16).toString('hex'))\"; done > /home/mbin/.mbin_secrets; for counter in {1..3}; do node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"; done >> /home/mbin/.mbin_secrets"

##
# First setup steps
##

cmd_exec "First setup steps - Clone git repository" \
"cd /var/www/mbin; git clone https://github.com/MbinOrg/mbin.git ."

cmd_exec "First setup steps - Create & configure media directory" \
"mkdir public/media; sudo chmod -R 775 public/medi; sudo chown -R mbin:www-data public/media"

cmd_exec "First setup steps - Configure var directory
Create & set permissions to the var directory (used for cache and log files)" \
"cd /var/www/mbin; mkdir var"

cmd_exec "First setup steps - Configure var directory - Get HTTPD username" \
"HTTPDUSER=\$(ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | awk '{print \$1}'); echo \$HTTPDUSER"
# Replaced cut with awk in the command above, because escpaing a litteral tab wasn't playing nice -AES

cmd_exec "First setup steps - Configure var directory - Set permissions for future files and folders" \
'sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:$(whoami):rwX var'

cmd_exec "First setup steps - Configure var directory - Set permissions on the existing files and folders" \
'sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:$(whoami):rwX var'

# Variable for path to .env file for testing -AES
ENV_PATH='/var/www/mbin/.env'
#ENV_PATH='/home/mbin/.test.env'

cmd_exec "First setup steps - The dot env file - Copy .env.example to .env for customization" \
"cp /var/www/mbin/.env.example "${ENV_PATH}

#cmd_exec "First setup steps - The dot env file - Load the secret keys into a variable, for use with future steps" \
#'SECRET_KEYS="$(cat ~/.mbin_secrets)"'
SECRET_KEYS="$(cat ~/.mbin_secrets)"

ENV_SUGGESTIONS_1="${ENV_PATH}
%name%=%value%
#
REDIS_PASSWORD $(echo "$SECRET_KEYS" | sed -n "3p")
APP_SECRET $(echo "$SECRET_KEYS" | sed -n "1p")
POSTGRES_PASSWORD $(echo "$SECRET_KEYS" | sed -n "4p")
RABBITMQ_PASSWORD $(echo "$SECRET_KEYS" | sed -n "2p")
MERCURE_JWT_SECRET \"$(echo "$SECRET_KEYS" | sed -n "5p")\"
"

cmd_exec "First setup steps - The dot env file - Service credentials - Review suggested ${ENV_PATH} configurations" \
'config_suggestions "$ENV_SUGGESTIONS_1"'

cmd_exec "First setup steps - The dot env file - 
INFORMATIONAL - View current postgres versions. Needed for future step." \
"pg_config --version; psql --version"

# Not sure if this is fool-proof. Not using it, but leaving in case it's desired.
POSTGRES_VERSION_GUESS=$(pg_config --version | awk -F'[ \.]' '{print $2}' 2>/dev/null)

cmd_exec "First setup steps - The dot env file - Define your server name in a variable for use in next steps
(ex: SERVER_NAME=subdomain.yourdomain.tld)" \
"SERVER_NAME="

# I'm skipping MAILER_DSN here because I didn't personally use it.
# Can be added later. -AES
ENV_SUGGESTIONS_2="${ENV_PATH}
%name%=%value%
#
SERVER_NAME $SERVER_NAME
KBIN_DOMAIN $SERVER_NAME
KBIN_STORAGE_URL https://$SERVER_NAME/media
KBIN_CONTACT_EMAIL mbin_admin@$SERVER_NAME
KBIN_SENDER_EMAIL mbin_mailer@$SERVER_NAME
KBIN_FEDERATION_ENABLED true
KBIN_REGISTRATIONS_ENABLED false
POSTGRES_VERSION
"

cmd_exec "First setup steps - The dot env file - Other important .env configs - Review suggested configurations" \
'config_suggestions "$ENV_SUGGESTIONS_2"'

cmd_exec "First setup steps - The dot env file - OAuth2 keys for API credential grants - Create an RSA key pair using OpenSSL
Note: If you protect the key with a passphrase, make sure to remember it! You will need it later" \
"cd /var/www/mbin; mkdir ./config/oauth2/; openssl genrsa -des3 -out ./config/oauth2/private.pem 4096"

cmd_exec "First setup steps - The dot env file - OAuth2 keys for API credential grants - Convert the RSA to PEM" \
"openssl rsa -in ./config/oauth2/private.pem --outform PEM -pubout -out ./config/oauth2/public.pem"

cmd_exec "First setup steps - The dot env file - OAuth2 keys for API credential grants
Generate a random hex string for the OAuth2 encryption key" \
"openssl rand -hex 16 > /home/mbin/.open_ssl_rand_hex"

ENV_SUGGESTIONS_3="${ENV_PATH}
%name%=%value%
#
OAUTH_PRIVATE_KEY %kernel.project_dir%/config/oauth2/private.pem
OAUTH_PUBLIC_KEY %kernel.project_dir%/config/oauth2/public.pem
OAUTH_PASSPHRASE
OAUTH_ENCRYPTION_KEY $(cat /home/mbin/.open_ssl_rand_hex)
"

cmd_exec "First setup steps - The dot env file - OAuth2 keys for API credential grants
Add the public and private key paths to .env
Note: If you set a passphrase when generating the RSA key, set it for OAUTH_PASSPHRASE
(e.g. 'OAUTH_PASSPHRASE=yourpassphrase'). Otherwise leave it blank (e.g. 'OAUTH_PASSPHRASE=')" \
'config_suggestions "$ENV_SUGGESTIONS_3"'

# Variable for path to php.ini file for testing -AES
PHP_INI_PATH='/etc/php/8.2/fpm/php.ini'

PHP_SUGGESTIONS_1="${PHP_INI_PATH}
%name% = %value%
;
upload_max_filesize 8M
post_max_size 8M
memory_limit 256M
realpath_cache_size 4096K
realpath_cache_ttl 600
"

##
# Service Configuration
##

cmd_exec "Service Configuration - PHP - Edit some PHP settings within your php.ini file" \
'config_suggestions "$PHP_SUGGESTIONS_1"'

PHP_SUGGESTIONS_2="${PHP_INI_PATH}
%name%=%value%
;
opcache.enable 1
opcache.enable_cli 1
opcache.memory_consumption 512
opcache.interned_strings_buffer 128
opcache.max_accelerated_files 100000
opcache.jit_buffer_size 500M
"
 
cmd_exec "Service Configuration - PHP - Optionally also enable OPCache for improved performances with PHP" \
'config_suggestions "$PHP_SUGGESTIONS_2"'

# Variable for path to www.conf file for testing -AES
WWW_CONF_PATH='/etc/php/8.2/fpm/pool.d/www.conf'

WWW_SUGGESTIONS_1="${WWW_CONF_PATH}
%name% = %value%
;
pm dynamic
pm.max_children 60
pm.start_servers 10
pm.min_spare_servers 5
pm.max_spare_servers 10
"
 
cmd_exec "Service Configuration - PHP - Edit your PHP www.conf file as well,
to increase the amount of PHP child processes (optional)
Note: These are personal preferences, adjust to your needs" \
'config_suggestions "$WWW_SUGGESTIONS_1"'

cmd_exec "Service Configuration - PHP - Be sure to restart (or reload) the PHP-FPM service to affect any changes." \
"sudo systemctl restart php8.2-fpm.service"

##
# Composer
##

# Reload previous choice, if available
COMPOSER_MODE=$(cat /home/mbin/.composer_mode 2>/dev/null)

cmd_exec "Composer - Mode select - Choose either 'dev' or 'prod', for use with the next steps.
Danger: When running in development mode your instance will make sensitive information available, such as database credentials, via the debug toolbar and/or stack traces. DO NOT expose your development instance to the Internet or you will have a bad time." \
"COMPOSER_MODE=$(cat /home/mbin/.composer_mode 2>/dev/null)"

# Save input as choice (unless this command was skipped,
#	in which case just save the current value, if available)
# Note: This is to allow skipping past this point. If you haven't
#	set a value yet, or it's still not valid, you can't skip
#	past this point
echo "${COMPOSER_MODE}" > /home/mbin/.composer_mode

cmd_exec "Composer - cd to /var/www/mbin" \
"cd /var/www/mbin"

if [[ "${COMPOSER_MODE}" = "prod" ]]; then
	cmd_exec "Composer - Composer Production - pt 1" \
	"composer install --no-dev"
	cmd_exec "Composer - Composer Production - pt 2" \
	"composer dump-env prod"
	cmd_exec "Composer - Composer Production - pt 3" \
	"APP_ENV=prod APP_DEBUG=0 php bin/console cache:clear"
	cmd_exec "Composer - Composer Production - pt 4" \
	"composer clear-cache"
elif [[ "${COMPOSER_MODE}" = "dev" ]]; then
	cmd_exec "Composer - Composer Development - pt 1" \
	"composer install"
	cmd_exec "Composer - Composer Development - pt 2" \
	"composer dump-env dev"
	cmd_exec "Composer - Composer Development - pt 3" \
	"APP_ENV=dev APP_DEBUG=1 php bin/console cache:clear"
	cmd_exec "Composer - Composer Development - pt 4" \
	"composer clear-cache"
else
	echo
	echo -e "\033[0;31mCritical halt:\033[0;34m COMPOSER_MODE must be set to either 'dev' or 'prod' to proceed."
	echo -e "Please restart this script and restart at step $((CMD_COUNT - 1));\033[0m"
	echo "bash install_mbin.bash $((CMD_COUNT - 1))"
	echo
	exit 1
fi

##
# Caching
##

# I'm leaning into Redis to keep the script simple. We can add an option for KeyDB later -AES

# Variable for path to redis.conf file for testing -AES
REDIS_CONF_PATH='/etc/redis/redis.conf'

# Get these again, in case we skipped to this step.
SECRET_KEYS="$(cat ~/.mbin_secrets)"

REDIS_SUGGESTIONS_1="${REDIS_CONF_PATH}
%name% %value%
#
requirepass $(echo "$SECRET_KEYS" | sed -n "3p")
supervised systemd
"
 
cmd_exec "Caching - Redis - Edit redis.conf file" \
'config_suggestions "$REDIS_SUGGESTIONS_1"'

cmd_exec "Caching - Redis - Restart Redis" \
"sudo systemctl restart redis.service"

##
# PostgreSQL
##

cmd_exec "PostgrSQL (Database) - Create new kbin database user using the password generated earlier.
Note: That password is $(echo "$SECRET_KEYS" | sed -n "4p") " \
"sudo -u postgres createuser --createdb --createrole --pwprompt kbin"

cmd_exec "PostgrSQL (Database) - Create tables and database structure - pt 1" \
"cd /var/www/mbin"

cmd_exec "PostgrSQL (Database) - Create tables and database structure - pt 2" \
"php bin/console doctrine:database:create"

cmd_exec "PostgreSQL (Database) - Create tables and database structure - pt 3" \
"php bin/console doctrine:migrations:migrate"

##
# RabbitMQ
##

cmd_exec "RabbitMQ - Install - Team RabbitMQ's main signing key" \
'curl -1sLf "https://keys.openpgp.org/vks/v1/by-fingerprint/0A9AF2115F4687BD29803A206B73A36E6026DFCA" | sudo gpg --dearmor | sudo tee /usr/share/keyrings/com.rabbitmq.team.gpg > /dev/null'

cmd_exec "RabbitMQ - Install - Community mirror of Cloudsmith: modern Erlang repository" \
"curl -1sLf https://ppa1.novemberain.com/gpg.E495BB49CC4BBE5B.key | sudo gpg --dearmor | sudo tee /usr/share/keyrings/rabbitmq.E495BB49CC4BBE5B.gpg > /dev/null"

cmd_exec "RabbitMQ - Install - Community mirror of Cloudsmith: RabbitMQ repository" \
"curl -1sLf https://ppa1.novemberain.com/gpg.9F4587F226208342.key | sudo gpg --dearmor | sudo tee /usr/share/keyrings/rabbitmq.9F4587F226208342.gpg > /dev/null"

# I admit that this is ugly as hell, but it's functional, and transparent. Needs refinement. -AES
cmd_exec "RabbitMQ - Install - Add apt repositories maintained by Team RabbitMQ to a text file in /home/mbin" \
'echo "## Provides modern Erlang/OTP releases" > /home/mbin/rabbitmq.list; \
echo -n "deb [signed-by=/usr/share/keyrings/rabbitmq.E495BB49CC4BBE5B.gpg] " >> /home/mbin/rabbitmq.list; \
echo "https://ppa1.novemberain.com/rabbitmq/rabbitmq-erlang/deb/ubuntu jammy main" >> /home/mbin/rabbitmq.list; \
echo -n "deb-src [signed-by=/usr/share/keyrings/rabbitmq.E495BB49CC4BBE5B.gpg] " >> /home/mbin/rabbitmq.list; \
echo "https://ppa1.novemberain.com/rabbitmq/rabbitmq-erlang/deb/ubuntu jammy main" >> /home/mbin/rabbitmq.list; \
echo "## Provides RabbitMQ" >> /home/mbin/rabbitmq.list; \
echo -n "deb [signed-by=/usr/share/keyrings/rabbitmq.9F4587F226208342.gpg] " >> /home/mbin/rabbitmq.list; \
echo "https://ppa1.novemberain.com/rabbitmq/rabbitmq-server/deb/ubuntu jammy main" >> /home/mbin/rabbitmq.list; \
echo -n "deb-src [signed-by=/usr/share/keyrings/rabbitmq.9F4587F226208342.gpg] " >> /home/mbin/rabbitmq.list; \
echo "https://ppa1.novemberain.com/rabbitmq/rabbitmq-server/deb/ubuntu jammy main" >> /home/mbin/rabbitmq.list'

cmd_exec "RabbitMQ - Install - Fix permissions/ownership of rabbitmq.list , and copy it to /etc/apt/sources.list.d/" \
"sudo chown root:root /home/mbin/rabbitmq.list; sudo chmod 644 /home/mbin/rabbitmq.list; sudo cp /home/mbin/rabbitmq.list /etc/apt/sources.list.d/"

cmd_exec "RabbitMQ - Install - Update package indices" \
"sudo apt-get update -y"

cmd_exec "RabbitMQ - Install - Install Erlang packages" \
"sudo apt-get install -y erlang-base erlang-asn1 erlang-crypto erlang-eldap erlang-ftp erlang-inets erlang-mnesia erlang-os-mon erlang-parsetools erlang-public-key erlang-runtime-tools erlang-snmp erlang-ssl erlang-syntax-tools erlang-tftp erlang-tools erlang-xmerl"

cmd_exec "RabbitMQ - Install - Install rabbitmq-server and its dependencies" \
"sudo apt-get install rabbitmq-server -y --fix-missing"

cmd_exec "RabbitMQ - Install - Add a new kbin user with the correct permissions" \
"sudo rabbitmqctl add_user 'kbin' '$(echo "$SECRET_KEYS" | sed -n "2p")'; \
sudo rabbitmqctl set_permissions -p '/' 'kbin' '.' '.' '.*'"

cmd_exec "RabbitMQ - Install - Remove the guest account" \
"sudo rabbitmqctl delete_user 'guest'"

ENV_SUGGESTIONS_4="${ENV_PATH}
%name%=%value%
#
MESSENGER_TRANSPORT_DSN amqp://kbin:\${RABBITMQ_PASSWORD}@127.0.0.1:5672/%2f/messages
"

cmd_exec "Configure Queue Messenger Handler" \
'config_suggestions "$ENV_SUGGESTIONS_4"'

##
# Setup Supervisor
##

cmd_exec "Supervisor - Install" \
"sudo apt-get install supervisor"

# Still ugly... -AES
cmd_exec "Supervisor - Add config to a text file in /home/mbin" \
'echo "[program:messenger]" > /home/mbin/messenger-worker.conf; \
echo "command=php /var/www/mbin/bin/console messenger:consume scheduler_default old async outbox deliver inbox resolve receive failed --time-limit=3600" >> /home/mbin/messenger-worker.conf; \
echo "user=www-data" >> /home/mbin/messenger-worker.conf; \
echo "numprocs=6" >> /home/mbin/messenger-worker.conf; \
echo "startsecs=0" >> /home/mbin/messenger-worker.conf; \
echo "autostart=true" >> /home/mbin/messenger-worker.conf; \
echo "autorestart=true" >> /home/mbin/messenger-worker.conf; \
echo "startretries=10" >> /home/mbin/messenger-worker.conf; \
echo "process_name=%(program_name)s_%(process_num)02d" >> /home/mbin/messenger-worker.conf'

cmd_exec "Supervisor - Fix permissions/ownership of messenger-worker.conf , and copy it to /etc/supervisor/conf.d/" \
"sudo chown root:root /home/mbin/messenger-worker.conf; sudo chmod 644 /home/mbin/messenger-worker.conf; sudo cp /home/mbin/messenger-worker.conf /etc/supervisor/conf.d/"

# Mercure is supposed to be here, but A: it's turned off by default and B: I was
#	specifically advised not to use it by an mbin admin. -AES

cmd_exec "Supervisor - Restart" \
"sudo supervisorctl reread && sudo supervisorctl update && sudo supervisorctl start all"

echo
echo "Process complete"
echo
