#!/bin/bash
#
# Listmonk Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
. /etc/federated
get_appvars

config_listmonk() {
  echo -ne "* Configuring listmonk container.."

  if [ ! -d "/federated/apps/listmonk" ]; then
    mkdir -p /federated/apps/listmonk/data/listmonk/static /federated/apps/listmonk/data/listmonk/uploads
  fi

  LISTMONK_SECRET=$(create_password)

cat > /federated/apps/listmonk/docker-compose.yml <<EOF
services:
  listmonk:
    image: listmonk/listmonk:\${IMAGE_VERSION}
    container_name: listmonk
    hostname: listmonk.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.21
    env_file:
      - ./.env
    volumes:
      - ./data/listmonk/config.toml:/listmonk/config.toml
      - ./data/listmonk/static:/listmonk/static
      - ./data/listmonk/uploads:/listmonk/uploads
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.listmonk.rule=Host(\`listmonk.$DOMAIN\`)"
      - "traefik.http.routers.listmonk.entrypoints=websecure"
      - "traefik.http.routers.listmonk.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

cat > /federated/apps/listmonk/.env <<EOF
IMAGE_VERSION="$(current_version listmonk)"
TZ=Etc/UTC
LISTMONK_ADMIN_USER=admin@$DOMAIN
LISTMONK_ADMIN_PASSWORD=$ADMINPASS
EOF

[[ "${PLUS}" = "true" ]] && sed -i "s/letsencrypt/httpresolver/g" /federated/apps/listmonk/docker-compose.yml

if [[ "${PLUS}" = "true" ]]; then
cat > /federated/apps/listmonk/data/listmonk/config.toml <<EOF
[app]
address = "0.0.0.0:9000"

# Database.
[db]
host = "postgresql.$DOMAIN"
port = 5432
user = "listmonk"
password = "$LISTMONK_SECRET"
database = "listmonk"
ssl_mode = "disable"
max_open = 25
max_idle = 25
max_lifetime = "300s"
EOF
else
cat > /federated/apps/listmonk/data/listmonk/config.toml <<EOF
[app]
address = "0.0.0.0:9000"

[db]
host = "postgresql.$DOMAIN"
port = 5432
user = "listmonk"
password = "$LISTMONK_SECRET"
database = "listmonk"
ssl_mode = "verify-full"
max_open = 25
max_idle = 25
max_lifetime = "300s"
EOF
fi
chmod 600 /federated/apps/listmonk/data/listmonk/config.toml /federated/apps/listmonk/.env

# Create database and user in postgresql
docker exec postgresql psql -U postgres -c "CREATE USER listmonk WITH PASSWORD '$LISTMONK_SECRET'" &> /dev/null
docker exec postgresql psql -U postgres -c "CREATE DATABASE listmonk" &> /dev/null
docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE listmonk TO listmonk" &> /dev/null
 
echo -ne "done.\n"
}
start_listmonk() {
  # Install the database scheme first
  docker compose -f /federated/apps/listmonk/docker-compose.yml run --rm listmonk ./listmonk --install --yes &> /dev/null

  # Change app.root_url and other settings to our domain if this a Core provision (not Plus)
  if [[ "${PLUS}" != "true" ]]; then
    docker exec postgresql psql -U listmonk -c "update settings set value='\"http://listmonk.$DOMAIN\"' where key='app.root_url'" &> /dev/null
    docker exec postgresql psql -U listmonk -c "update settings set value='\"listmonk <listmonk@listmonk.$DOMAIN>\"' where key='app.from_email'" &> /dev/null
    docker exec postgresql psql -U listmonk -c "update settings set value='[{\"host\": \"mail.$DOMAIN\", \"port\": 587, \"enabled\": true, \"password\": \"$ADMINPASS\", \"tls_type\": \"STARTTLS\", \"username\": \"fcore\", \"max_conns\": 10, \"idle_timeout\": \"15s\", \"wait_timeout\": \"5s\", \"auth_protocol\": \"login\", \"email_headers\": [], \"hello_hostname\": \"\", \"max_msg_retries\": 2, \"tls_skip_verify\": false}, {\"host\": \"smtp.gmail.com\", \"port\": 465, \"enabled\": false, \"password\": \"password\", \"tls_type\": \"TLS\", \"username\": \"username@gmail.com\", \"max_conns\": 10, \"idle_timeout\": \"15s\", \"wait_timeout\": \"5s\", \"auth_protocol\": \"login\", \"email_headers\": [], \"hello_hostname\": \"\", \"max_msg_retries\": 2, \"tls_skip_verify\": false}]' where key='smtp';" &> /dev/null
  fi

  # Start service with command to make sure it's up before proceeding
  start_service "listmonk" "nc -z 192.168.0.21 9000 &> /dev/null" "8"

  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil add-record $DOMAIN listmonk A 86400 $EXTERNALIP &> /dev/null

  echo -ne "done."
}
email_listmonk() {
  echo -ne "* Sending email to customer.."

cat > /federated/apps/mail/data/root/certs/mailfile <<EOF
<html>
<img src="https://www.federated.computer/wp-content/uploads/2023/11/logo.png" alt="" /><br>
<p>
<h4>Listmonk is now installed on $DOMAIN</h4>
<p>
Here is your applications chart with on how to access this service:<br>
<p>
<h4>Applications</h4>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-cul6{border-color:inherit;color:#340096;text-align:left;text-decoration:underline;vertical-align:top}
.tg .tg-acii{background-color:#FFF;border-color:inherit;color:#333;text-align:left;vertical-align:top}
.tg .tg-0hty{background-color:#000000;border-color:inherit;color:#ffffff;font-weight:bold;text-align:left;vertical-align:top}
.tg .tg-kwiq{border-color:inherit;color:#000000;text-align:left;vertical-align:top;word-wrap:break-word}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
</style>
<table class="tg" style="undefined;table-layout: fixed; width: 996px">
<colgroup>
<col style="width: 101.333333px">
<col style="width: 203.333333px">
<col style="width: 282.333333px">
<col style="width: 185.33333px">
<col style="width: 78.333333px">
<col style="width: 220.333333px">
</colgroup>
<thead>
  <tr>
    <th class="tg-0hty">Service</th>
    <th class="tg-0hty">Link</th>
    <th class="tg-0hty">User / Pass</th>
    <th class="tg-0hty">Access</th>
    <th class="tg-0hty">Docs</th>
    <th class="tg-0hty">Description</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-kwiq">Listmonk</td>
    <td class="tg-kwiq"><a href="https://listmonk.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">listmonk.$DOMAIN</span></a></td>
    <td class="tg-kwiq">admin@$DOMAIN<br>$ADMINPASS</td>
    <td class="tg-kwiq">User access is separate from panel</td>
    <td class="tg-kwiq"><a href="https://documentation.federated.computer/docs/getting_started/welcome/" target="_blank" rel="noopener noreferrer"><span style="color:#340096">Click here</span></a></td>
    <td class="tg-kwiq">Listmonk is (a replacement for Mailchimp) is used to create e-mail subscription lists</td>
  </tr>
</tbody>
</table>
<h4>Thanks for your support!</h4>
<p>
Thank you for your support of Federated Computer. We really appreciate it and hope you have a very successful
time with Federated Core.
<p>
Again, if we can be of any assistance, please don't hesitate to get in touch.
<p>
Support: https://support.federated.computer<br>
Phone: (970) 722-8715<br>
Email: support@federated.computer<br>
<p>
It's <b>your</b> computer. Let's make it work for you!
</html>
EOF

  # Send out e-mail from mail container with details
  docker exec mail bash -c "mail -r admin@$DOMAIN -a \"Content-type: text/html\" -s \"Application installed on $DOMAIN\" $EMAIL < /root/certs/mailfile"
  rm /federated/apps/mail/data/root/certs/mailfile

  echo -ne "done.\n"
}
uninstall_listmonk() {
  echo -ne "* Uninstalling listmonk container.."

  # First stop the service
  cd /federated/apps/listmonk && docker compose -f docker-compose.yml -p listmonk down &> /dev/null

  # Delete database and user in postgresql
  docker exec postgresql psql -U postgres -c "DROP DATABASE listmonk" &> /dev/null
  docker exec postgresql psql -U postgres -c "DROP USER listmonk" &> /dev/null

  # Delete the app directory
  rm -rf /federated/apps/listmonk

  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil delete-rrset $DOMAIN listmonk A &> /dev/null

  echo -ne "done.\n"
}
