#!/bin/bash
#
# Roundcube Service

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

config_roundcube() {
  echo -ne "* Configuring roundcube container.."

  if [ ! -d "/federated/apps/roundcube" ]; then
    mkdir -p /federated/apps/roundcube/data/var/www/html
  fi

cat > /federated/apps/roundcube/docker-compose.yml <<EOF
services:
  roundcube:
    image: roundcube/roundcubemail:\${IMAGE_VERSION}
    container_name: roundcube
    hostname: roundcube.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.47
    extra_hosts:
      - "authelia.$DOMAIN:$EXTERNALIP"
    env_file:
      - ./.env
    volumes:
      - ./data/var/www/html:/var/www/html
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.roundcube.rule=Host(\`roundcube.$DOMAIN\`) || Host(\`webmail.$DOMAIN\`)"
      - "traefik.http.routers.roundcube.entrypoints=websecure"
      - "traefik.http.routers.roundcube.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

ROUNDCUBE_SECRET=$(create_password);

cat > /federated/apps/roundcube/.env <<EOF
IMAGE_VERSION="$(current_version roundcube)"
ROUNDCUBEMAIL_DB_TYPE=mysql
ROUNDCUBEMAIL_DB_HOST=pdnsmysql.$DOMAIN
ROUNDCUBEMAIL_DB_USER=roundcube
ROUNDCUBEMAIL_DB_NAME=roundcube
ROUNDCUBEMAIL_DB_PASSWORD=$ROUNDCUBE_SECRET
ROUNDCUBEMAIL_SKIN=elastic
ROUNDCUBEMAIL_DEFAULT_HOST=tls://mail.$DOMAIN
ROUNDCUBEMAIL_SMTP_SERVER=tls://mail.$DOMAIN
ROUNDCUBEMAIL_USERNAME_DOMAIN=$DOMAIN
ROUNDCUBEMAIL_UPLOAD_MAX_FILESIZE=4G
EOF
chmod 600 /federated/apps/roundcube/.env

# Create database and user in mysql
/federated/bin/fix pdnsmysql
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'create database roundcube;'" &> /dev/null
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e \"CREATE USER 'roundcube'@'%' IDENTIFIED BY '$ROUNDCUBE_SECRET';\"" &> /dev/null
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e \"grant all privileges on roundcube.* to 'roundcube'@'%';\"" &> /dev/null
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'flush privileges;'" &> /dev/null
 
echo -ne "done.\n"
}
start_roundcube() {
  # Start service with command to make sure it's up before proceeding
  start_service "roundcube" "nc -z 192.168.0.47 80 &> /dev/null" "7"

  /federated/bin/fix pdnsmysql
  docker exec pdns pdnsutil add-record $DOMAIN roundcube A 86400 $EXTERNALIP &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't add dns record for roundcube"
  docker exec pdns pdnsutil add-record $DOMAIN webmail A 86400 $EXTERNALIP &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't add dns record for roundcube"

  echo -ne "done.\n"
}
email_roundcube() {
  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>Roundcube is now installed on $DOMAIN</h4>
<p>
Dear Customer,<br>
<br>
We'd like to introduce you to "Roundcube", a free and open source webmail solution with a desktop-like user interface. You can find "Roundcube" at <a href="https://roundcube.$DOMAIN">https://roundcube.$DOMAIN</a>
and also on your Dashboard <a href="https://dashboard.$DOMAIN">https://dashboard.$DOMAIN</a> as a new application.
<br>
<br>
This is only one of a number of big changes you'll be seeing from Federated Computer in the coming months to improve and enhance your Federated Core. Thank you for being a customer!
<br>
<br>
Best,
<br>
Federated Computer
<p>
</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_roundcube() {
  echo -ne "* Uninstalling roundcube container.."

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

  # Delete database and user
  docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'drop database roundcube;'" &> /dev/null
  docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'drop user roundcube;'" &> /dev/null

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

  # Delete the image
  docker image rm roundcube/roundcubemail:$IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  docker exec pdns pdnsutil delete-rrset $DOMAIN roundcube A
  docker exec pdns pdnsutil delete-rrset $DOMAIN webmail A

  # Uninstall the SSO configuration if it exists in authelia (authelia must exist too)
  if [[ $(grep "### Roundcube" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]]; then
    sed -i '/### Roundcube/,/### /{/### PowerDNS/!{/### /!d}}' /federated/apps/authelia/data/config/idproviders.yml
    sed -i '/### Roundcube/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_roundcube() {
  echo -ne "* Configuring roundcube 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 "### Roundcube" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]] && failcheck "Authelia already has a Roundcube configuration."

  ROUNDCUBE_CLIENT_SECRET=$(create_password);
  ROUNDCUBE_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $ROUNDCUBE_CLIENT_SECRET | awk '{ print $2 }')

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
     ### Roundcube
      - client_id: 'roundcube'
        client_name: 'Roundcube'
        client_secret: $ROUNDCUBE_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - https://roundcube.$DOMAIN/index.php/login/oauth
        scopes:
          - 'openid'
          - 'profile'
          - 'email'
        userinfo_signed_response_alg: 'none'
        token_endpoint_auth_method: 'client_secret_post'
EOF

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

  # Add in extra hosts config
  add_authelia_config_to_dockercompose "roundcube" "$EXTERNALIP"
  add_authelia_config_to_dockercompose "mail" "$EXTERNALIP"

sed -i "/?php/a \    \$config['oauth_provider'] = 'generic'; \n\
    \$config['oauth_provider_name'] = 'Authelia'; \n\
    \$config['oauth_client_id'] = 'roundcube'; \n\
    \$config['oauth_client_secret'] = '$ROUNDCUBE_CLIENT_SECRET'; \n\
    \$config['oauth_auth_uri'] = 'https://authelia.$DOMAIN/api/oidc/authorization'; \n\
    \$config['oauth_token_uri'] = 'https://authelia.$DOMAIN/api/oidc/token'; \n\
    \$config['oauth_identity_uri'] = 'https://authelia.$DOMAIN/api/oidc/userinfo'; \n\
    \$config['oauth_identity_fields'] = ['email']; \n\
    \$config['oauth_verify_peer'] = false; \n\
    \$config['use_https'] = true; \n\
    \$config['oauth_scope'] = 'email openid profile'; \n\
    \$config['oauth_login_redirect'] = false;"  /federated/apps/roundcube/data/var/www/html/config/config.inc.php

# Disable Spamassasin, enable Rspamd, and insert OAUTH2 configuration in mail server
sed -i "s/ENABLE_SPAMASSASSIN=.*/ENABLE_SPAMASSASSIN=0/g" /federated/apps/mail/.env
sed -i "s/ENABLE_SPAMASSASSIN_KAM=.*/#ENABLE_SPAMASSASSIN_KAM=0/g" /federated/apps/mail/.env
sed -i "s/SPAMASSASSIN_SPAM_TO_INBOX=.*/#SPAMASSASSIN_SPAM_TO_INBOX=0/g" /federated/apps/mail/.env
sed -i "s/ENABLE_AMAVIS=.*/ENABLE_AMAVIS=0/g" /federated/apps/mail/.env
sed -i "s/ENABLE_CLAMAV=.*/ENABLE_CLAMAV=1/g" /federated/apps/mail/.env
sed -i "s/ENABLE_POSTGREY=.*/ENABLE_POSTGREY=0/g" /federated/apps/mail/.env
sed -i "/ENABLE_POSTGREY=0/a  \ENABLE_RSPAMD=1\nRSPAMD_GREYLISTING=1\nENABLE_AMAVIS=0" /federated/apps/mail/.env
sed -i "/LOG_LEVEL=debug/a  \ENABLE_OAUTH2=1\nOAUTH2_INTROSPECTION_URL=https://roundcube:$ROUNDCUBE_CLIENT_SECRET@authelia.$DOMAIN/api/oidc/introspection\nOAUTH2_USERNAME_ATTRIBUTE=username\nOAUTH2_INTROSPECTION_MODE=post" /federated/apps/mail/.env

cat > /federated/apps/mail/data/tmp/docker-mailserver/postfix-main.cf <<'EOF'
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
EOF

[[ ! -d "/federated/apps/mail/data/etc/dovecot/conf.d" ]] && mkdir -p /federated/apps/mail/data/etc/dovecot/conf.d
cat > /federated/apps/mail/data/etc/dovecot/conf.d/95-roundcube.conf <<'EOF'
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0666
    user = postfix
  }
}
EOF

[[ ! $(grep 95-roundcube.conf /federated/apps/mail/docker-compose.yml 2>/dev/null) ]] && sed -i "/volumes:/a  \      - ./data/etc/dovecot/conf.d/95-roundcube.conf:/etc/dovecot/conf.d/95-roundcube.conf" /federated/apps/mail/docker-compose.yml

sed -i "s/ENABLE_SASLAUTHD=.*/ENABLE_SASLAUTHD=0/g" /federated/apps/mail/.env
sed -i "s/SASLAUTHD_MECHANISMS=.*/SASLAUTHD_MECHANISMS=rimap/g" /federated/apps/mail/.env
sed -i "/SASLAUTHD_MECHANISMS=rimap/a  \SASLAUTHD_MECH_OPTIONS=127.0.0.1" /federated/apps/mail/.env
sed -i "s/SASLAUTHD_LDAP_SERVER=.*/#SASLAUTHD_LDAP_SERVER=ldap:\/\/ldap.$DOMAIN/g" /federated/apps/mail/.env
sed -i "s/SASLAUTHD_LDAP_BIND_DN=.*/#SASLAUTHD_LDAP_BIND_DN=cn=admin,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST/g" /federated/apps/mail/.env
sed -i "s/SASLAUTHD_LDAP_PASSWORD=.*/#SASLAUTHD_LDAP_PASSWORD=$LDAP_SECRET/g" /federated/apps/mail/.env
sed -i "s/SASLAUTHD_LDAP_SEARCH_BASE=.*/#SASLAUTHD_LDAP_SEARCH_BASE=ou=people,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST/g" /federated/apps/mail/.env
sed -i 's/SASLAUTHD_LDAP_FILTER=.*/#SASLAUTHD_LDAP_FILTER=\(\&\(objectClass\=inetOrgPerson\)\(mail\=\%U\@\%r\)\)/g' /federated/apps/mail/.env
sed -i 's/DOVECOT_PASS_FILTER=.*/DOVECOT_PASS_FILTER=\(\|\(mail\=\%u\)\(uid\=\%u\)\)/g' /federated/apps/mail/.env
sed -i 's/DOVECOT_USER_FILTER=.*/DOVECOT_USER_FILTER=\(\|\(mail\=\%u\)\(uid\=\%u\)\)/g' /federated/apps/mail/.env

  run_command "/federated/bin/stop roundcube"
  run_command "/federated/bin/start roundcube"
  run_command "/federated/bin/stop mail"
  run_command "/federated/bin/start mail"

  echo -ne "done.\n"
}
