#!/bin/bash
#
# Matrix Service

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

config_matrix() {
  echo -ne "* Configuring matrix container.."

  if [ ! -d "/federated/apps/matrix" ]; then
    mkdir -p /federated/apps/matrix/data/matrix &> /dev/null
    if [[ "${PLUS}" != "true" ]]; then
      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
    fi
    chown -R 991:991 /federated/apps/matrix/data/matrix
  fi

  MATRIX_SECRET=$(create_password);

cat > /federated/apps/matrix/docker-compose.yml <<EOF
services:
  matrix:
    image: matrixdotorg/synapse:\${IMAGE_VERSION}
    container_name: matrix
    hostname: matrix.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.19
    volumes:
     - ./data/matrix:/data
    extra_hosts:
      - "authelia.$DOMAIN:$EXTERNALIP"
    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:
  core:
    external: true
EOF

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

cat > /federated/apps/matrix/.env <<EOF
IMAGE_VERSION="$(current_version matrix)"
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
if [[ "${PLUS}" = "true" ]]; then
cat >> /federated/apps/matrix/data/matrix/homeserver.yaml <<EOF

web_client_location: https://element.$DOMAIN/
public_baseurl: https://matrix.$DOMAIN/
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
EOF
else
cat >> /federated/apps/matrix/data/matrix/homeserver.yaml <<EOF

web_client_location: https://element.$DOMAIN/
public_baseurl: https://matrix.$DOMAIN/
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

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.\n"
}
start_matrix() {
  # Start service with command to make sure it's up before proceeding
  start_service "matrix" "nc -z 192.168.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

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

  echo -ne "done.\n"
}
email_matrix() {
  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>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

  echo -ne "done.\n"
}
uninstall_matrix() {
  echo -ne "* Uninstalling matrix container.."

  # 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

  # Delete the image
  docker image rm matrixdotorg/synapse:$IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil delete-rrset $DOMAIN matrix A

  # Uninstall the SSO configuration if it exists in authelia (authelia must exist too)
  if [[ $(grep "### Matrix" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]]; then
    sed -i '/### Matrix/,/### /{/### PowerDNS/!{/### /!d}}' /federated/apps/authelia/data/config/idproviders.yml
    sed -i '/### Matrix/d' /federated/apps/authelia/data/config/idproviders.yml
    run_command "/federated/bin/stop authelia"
    run_command "/federated/bin/start authelia"
  fi

  echo -ne "done.\n"
}
configsso_matrix() {
  if [[ "${PLUS}" != "true" ]]; then
  echo -ne "* Configuring matrix container with SSO.."

  [ ! -d "/federated/apps/authelia" ] && failcheck "Authelia is not installed. You need this first before continuing."
  [ ! -f "/federated/apps/authelia/data/config/idproviders.yml" ] && failcheck "Authelia idproviders.yml is missing."
  [[ $(grep "### Matrix" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]] && failcheck "Authelia already has a Matrix configuration."

  MATRIX_CLIENT_SECRET=$(create_password);
  MATRIX_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $MATRIX_CLIENT_SECRET | awk '{ print $2 }')
  echo "$MATRIX_CLIENT_SECRET" > /federated/apps/matrix/.matrix.client.secret

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
      ### Matrix
      - client_id: 'matrix'
        client_name: 'Matrix'
        client_secret: $MATRIX_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - 'https://matrix.$DOMAIN/_synapse/client/oidc/callback'
        scopes:
          - 'openid'
          - 'profile'
          - 'email'
        userinfo_signed_response_alg: 'none'
EOF

  # Restart Authelia for changes to take the above configuration
  run_command "/federated/bin/stop authelia"
  run_command "/federated/bin/start authelia"

  add_authelia_config_to_dockercompose "matrix" "$EXTERNALIP"

cat >> /federated/apps/matrix/data/matrix/homeserver.yaml <<EOF
oidc_providers:
  - idp_id: authelia
    idp_name: "Authelia"
    idp_icon: "mxc://authelia.com/cKlrTPsGvlpKxAYeHWJsdVHI"
    discover: true
    issuer: "https://authelia.$DOMAIN"
    client_id: "matrix"
    client_secret: "$MATRIX_CLIENT_SECRET"
    scopes: ["openid", "profile", "email"]
    allow_existing_users: true
    user_mapping_provider:
      config:
        subject_claim: "sub"
        localpart_template: "{{ user.name }}"
        display_name_template: "{{ user.name }}"
        email_template: "{{ user.email }}"
EOF

  # Restart Matrix for changes to take the above configuration
  run_command "/federated/bin/stop matrix"
  run_command "/federated/bin/start matrix"

  echo -ne "done.\n"
  fi
}
configsso_matrix_plus() {
  MATRIX_CLIENT_SECRET=$(cat /federated/apps/matrix/.matrix.client.secret)

cat >> /federated/apps/matrix/data/matrix/homeserver.yaml <<EOF
oidc_providers:
  - idp_id: authelia
    idp_name: "Authelia"
    idp_icon: "mxc://authelia.com/cKlrTPsGvlpKxAYeHWJsdVHI"
    discover: true
    issuer: "https://authelia.$DOMAIN"
    client_id: "matrix"
    client_secret: "$MATRIX_CLIENT_SECRET"
    scopes: ["openid", "profile", "email"]
    allow_existing_users: true
    user_mapping_provider:
      config:
        subject_claim: "sub"
        localpart_template: "{{ user.name }}"
        display_name_template: "{{ user.name }}"
        email_template: "{{ user.email }}"
EOF

  # Restart Matrix for changes to take the above configuration
  run_command "/federated/bin/stop matrix"
  run_command "/federated/bin/start matrix"
}
