#!/bin/bash
#
# Matrix Service

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

config_matrix() {
  echo -ne "\n* Configuring /federated/apps/matrix container.."

  if [ ! -d "/federated/apps/matrix" ]; then
    mkdir -p /federated/apps/matrix/data/matrix &> /dev/null
    cp /federated/certs/certs/$DOMAIN.crt /federated/certs/private/$DOMAIN.key /federated/apps/matrix/data/matrix/
    chmod 644 /federated/apps/matrix/data/matrix/$DOMAIN.crt /federated/apps/matrix/data/matrix/$DOMAIN.key
    chown -R 991:991 /federated/apps/matrix/data/matrix
  fi

  MATRIX_SECRET=$(create_password);

cat > /federated/apps/matrix/docker-compose.yml <<EOF
version: '3.7'

services:
  matrix:
    image: matrixdotorg/synapse:\${IMAGE_VERSION}
    container_name: matrix
    hostname: matrix.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.19
    volumes:
     - ./data/matrix:/data
    env_file:
      - ./.env
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.matrix.rule=Host(\`matrix.$DOMAIN\`)"
      - "traefik.http.routers.matrix.entrypoints=websecure"
      - "traefik.http.routers.matrix.tls.certresolver=letsencrypt"

networks:
  federated:
    external: true
EOF

cat > /federated/apps/matrix/.env <<EOF
IMAGE_VERSION="v1.100.0"
EOF
chmod 600 /federated/apps/matrix/.env

# Generate the matrix homeserver.yaml file
docker run --rm -v "/federated/apps/matrix/data/matrix:/data" -e SYNAPSE_SERVER_NAME=matrix.$DOMAIN -e SYNAPSE_REPORT_STATS=yes matrixdotorg/synapse:latest generate &> /dev/null
[ $? -ne 0 ] && fail "Couldn't run docker matrixdotorg/synapse:latest generate"

# Take out default Sqlite database config
sed -i 's!database: /data/homeserver.db!!g' /federated/apps/matrix/data/matrix/homeserver.yaml
sed -i 's!database:!!g' /federated/apps/matrix/data/matrix/homeserver.yaml
sed -i 's!name: sqlite3!!g' /federated/apps/matrix/data/matrix/homeserver.yaml
sed -i 's!args:!!g' /federated/apps/matrix/data/matrix/homeserver.yaml

# Insert our Postgres and LDAP config
cat >> /federated/apps/matrix/data/matrix/homeserver.yaml <<EOF

serve_server_wellknown: true
turn_uris: [ "turn:turn.$DOMAIN?transport=udp", "turn:turn.$DOMAIN?transport=tcp" ]
turn_shared_secret: "$COTURN_MATRIX_SECRET"
turn_user_lifetime: 86400000
database:
    name: psycopg2
    args:
        user: matrix
        password: $MATRIX_SECRET
        host: postgresql.$DOMAIN
        database: matrix
        cp_min: 5
        cp_max: 10
email:
  smtp_host: "mail.$DOMAIN"
  smtp_port: 587
  smtp_user: "$SMTPUSER"
  smtp_pass: "$ADMINPASS"
  force_tls: true
  #  require_transport_security: true
  enable_tls: true
  notif_from: "Your Friendly %(app)s homeserver <matrix@matrix.$DOMAIN>"
  app_name: $COMPANY Matrix Server

modules:
  - module: "ldap_auth_provider.LdapAuthProviderModule"
    config:
      enabled: true
      uri: "ldaps://ldap.$DOMAIN:636"
      start_tls: true
      base: "dc=federatedcomputer,dc=cloud"
      attributes:
        mail: "mail"
        uid: "uid"
        name: "givenName"
      bind_dn: cn=admin,dc=federatedcomputer,dc=cloud
      bind_password: $LDAP_SECRET
      tls_options:
        validate: true
        local_certificate_file: /data/$DOMAIN.crt
        local_private_key_file: /data/$DOMAIN.key
EOF

# Set the ldap configuration correct to the domain
if [ "${#LDAP_DOMAIN_ARRAY[@]}" -eq "3" ]; then
  sed -i "s#dc=federatedcomputer,dc=cloud#dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_MIDDLE,dc=$LDAP_DOMAIN_LAST#g" /federated/apps/matrix/data/matrix/homeserver.yaml
else
  sed -i "s#dc=federatedcomputer,dc=cloud#dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST#g" /federated/apps/matrix/data/matrix/homeserver.yaml
fi

# Set permissions
chown -R 991:991 /federated/apps/matrix/data/matrix

# Create database and user in postgresql
docker exec postgresql psql -U postgres -c "CREATE USER matrix WITH PASSWORD '$MATRIX_SECRET'" &> /dev/null
docker exec postgresql psql -U postgres -c "CREATE DATABASE matrix" &> /dev/null
docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE matrix TO matrix" &> /dev/null

echo -ne "done."
}
start_matrix() {
  # Start service with command to make sure it's up before proceeding
  start_service "matrix" "nc -z 172.99.0.19 8008 &> /dev/null" "8"

  # Set permissions
  chown -R 991:991 /federated/apps/matrix/data/matrix

  # Set admin user as admin in Matrix
  docker exec postgresql psql -U matrix -c "update users set admin='1' where name='\"@admin:matrix.$DOMAIN\"'" &> /dev/null

  docker exec pdns pdnsutil add-record $DOMAIN matrix A 86400 $EXTERNALIP &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't add dns record"


  echo -ne "done."
}
email_matrix() {
  echo -ne "* Sending email to customer.."
  spin &
  SPINPID=$!

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>Wordpress 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">Matrix</td>
    <td class="tg-kwiq"><a href="https://element.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">element.$DOMAIN</span></a></td>
    <td class="tg-kwiq">admin@$DOMAIN<br>$ADMINPASS</td>
    <td class="tg-kwiq">All users in panel have access using user@$DOMAIN</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">Matrix (a Slack replacement) provides you the ability to chat with those on your team and outside of your team</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

  kill -9 $SPINPID &> /dev/null
  echo -ne "done.\n"
}
uninstall_matrix() {
  echo -ne "* Uninstalling matrix container.."
  spin &
  SPINPID=$!

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

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

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

  kill -9 $SPINPID &> /dev/null
  echo -ne "done.\n"
}
