#!/bin/bash
source ./scripts/make/constants

printf "Installing MMPM Daemons\n"

log_notice

log_action "Installing MMPM Daemons"

printf " -- configuring MMPM systemd services"

U=$(id -u -n)
GUNICORN_EXECUTABLE=$HOME/.local/bin/gunicorn
WSSH_EXECUTABLE=$HOME/.local/bin/wssh

log_and_eval "sudo cp -r mmpm/etc /etc"

log_action "Substituting 'SUBSTITUTE_user' for $U in /etc/systemd/system/mmpm.service"

sudo sed -i "s~SUBSTITUTE_user~$U~g" /etc/systemd/system/mmpm.service

log_action "Substituting 'SUBSTITUTE_user' for $U in /etc/systemd/system/mmpm-webssh.service"
sudo sed -i "s~SUBSTITUTE_user~$U~g" /etc/systemd/system/mmpm-webssh.service

log_action "Substituting 'SUBSTITUTE_gunicorn' for $GUNICORN_EXECUTABLE in /etc/systemd/system/mmpm.service"
sudo sed -i "s~SUBSTITUTE_gunicorn~$GUNICORN_EXECUTABLE~g" /etc/systemd/system/mmpm.service

log_action "Substituting 'SUBSTITUTE_wssh' for $WSSH_EXECUTABLE in /etc/systemd/system/mmpm-webssh.service"
sudo sed -i "s~SUBSTITUTE_wssh~$WSSH_EXECUTABLE~g" /etc/systemd/system/mmpm-webssh.service

log_and_eval "sudo systemctl enable mmpm mmpm-webssh" # prints to stdout regardless

printf " -- starting MMPM systemd services"
log_and_eval "sudo systemctl start mmpm mmpm-webssh"
_done_

log_and_eval "sudo systemctl status mmpm --no-pager" # just for log keeping
log_and_eval "sudo systemctl status mmpm-webssh --no-pager" # just for log keeping

printf " -- configuring NGINX service files"
log_and_eval "sudo ln -sfv /etc/nginx/sites-available/mmpm.conf /etc/nginx/sites-enabled"
_done_

printf " -- restarting NGINX service"
log_and_eval "sudo systemctl restart nginx.service --no-pager"
_done_

printf "MMPM GUI Installed\n"

log_action "MMPM GUI Installed"

printf "\nThe MMPM GUI is being served the IP address of your default interface at port $MMPM_PROXY_PORT"
printf "\nBest guess: http://$MMPM_HOST_IP:$MMPM_PROXY_PORT\n"
printf "\nYou may also place an entry for the MMPM Host IP address in your /etc/hosts file, ie. '$MMPM_HOST_IP mmpm'\n"

