#!/bin/bash
#
# Wordpress Service

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

config_wordpress() {
  echo -ne "* Configuring wordpress container.."

  if [ ! -d "/federated/apps/wordpress" ]; then
    mkdir -p /federated/apps/wordpress/data/bitnami/wordpress
    chown -R 1001 /federated/apps/wordpress/data/bitnami/wordpress
  fi

  WORDPRESS_SECRET=$(create_password);

cat > /federated/apps/wordpress/docker-compose.yml <<EOF
services:
 wordpress:
    image: bitnami/wordpress:\${IMAGE_VERSION}
    container_name: wordpress
    hostname: wordpress.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.34
    env_file:
      - ./.env
    extra_hosts:
      - "www.$DOMAIN:$EXTERNALIP"
      - "listmonk.$DOMAIN:$EXTERNALIP"
      - "authelia.$DOMAIN:$EXTERNALIP"
    volumes:
      - ./data/bitnami/wordpress:/bitnami/wordpress
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.wordpress.rule=Host(\`www.$DOMAIN\`) || Host(\`$DOMAIN\`) || Host(\`wordpress.$DOMAIN\`)"
      - "traefik.http.routers.wordpress.entrypoints=websecure"
      - "traefik.http.routers.wordpress.tls.certresolver=letsencrypt"
      - "traefik.http.services.wordpress.loadbalancer.server.port=8080"

networks:
  core:
    external: true
EOF

cat > /federated/apps/wordpress/.env <<EOF
IMAGE_VERSION="$(current_version wordpress)"
WORDPRESS_USERNAME=admin@$DOMAIN
WORDPRESS_PASSWORD=$ADMINPASS
WORDPRESS_EMAIL=admin@$DOMAIN
WORDPRESS_FIRST_NAME=Admin
WORDPRESS_LAST_NAME=Wordpress
WORDPRESS_BLOG_NAME="$COMPANY Blog"
WORDPRESS_DATABASE_HOST=pdnsmysql.$DOMAIN
WORDPRESS_DATABASE_PORT_NUMBER=3306
WORDPRESS_DATABASE_USER=wordpress
WORDPRESS_DATABASE_NAME=wordpress
WORDPRESS_DATABASE_PASSWORD=$WORDPRESS_SECRET
WORDPRESS_SMTP_HOST=mail.$DOMAIN
WORDPRESS_SMTP_PORT=587
WORDPRESS_SMTP_USER=$SMTPUSER@$DOMAIN
WORDPRESS_SMTP_PASSWORD=$ADMINPASS
PHP_DEFAULT_UPLOAD_MAX_FILESIZE=2048M
PHP_DEFAULT_POST_MAX_SIZE=2048M
PHP_UPLOAD_MAX_FILESIZE=2048M
PHP_POST_MAX_SIZE=2048M
EOF
chmod 600 /federated/apps/wordpress/.env

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

  chmod -R 755 /federated/apps/wordpress/data/bitnami/wordpress/wp-content
  chmod 740 /federated/apps/wordpress/data/bitnami/wordpress/wp-config.php
  sed -i s#http://#https://#g /federated/apps/wordpress/data/bitnami/wordpress/wp-config.php

  run_command "/federated/bin/stop wordpress"
  run_command "/federated/bin/start wordpress"
  run_command "docker exec pdns pdnsutil add-record $DOMAIN www A 86400 $EXTERNALIP"
  run_command "docker exec pdns pdnsutil add-record $DOMAIN wordpress A 86400 $EXTERNALIP"

  # Install cronjob
  (crontab -l 2>/dev/null; echo "30 * * * * /federated/bin/check-wordpressversion > /dev/null 2>&1") | sort -u | crontab -

  echo -ne "done.\n"
}
email_wordpress() {
  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">Wordpress</td>
    <td class="tg-kwiq"><a href="https://www.$DOMAIN/login" target="_blank" rel="noopener noreferrer"><span style="color:#340096">www.$DOMAIN/login</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">Wordpress is a dynamic content management solution used by 10s of millions of websites around the globe</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_wordpress() {
  echo -ne "* Uninstalling wordpress container.."

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

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

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

  # Delete the image
  docker image rm bitnami/wordpress:$IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  docker exec pdns pdnsutil delete-rrset $DOMAIN wordpress A
  docker exec pdns pdnsutil delete-rrset $DOMAIN www A

  # Remove cronjob
  crontab -l | grep -v '/federated/bin/check-wordpressversion'  | crontab -

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

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

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
     ### Wordpress
      - client_id: 'wordpress'
        client_name: 'WordPress'
        client_secret: $WORDPRESS_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - 'https://$DOMAIN/wp-admin/admin-ajax.php?action=openid-connect-authorize'
        scopes:
          - 'openid'
          - 'profile'
          - 'email'
          - 'groups'
        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_authelia_config_to_dockercompose "wordpress" "$EXTERNALIP"

sed -i "/Add any custom values/a \
define( 'OIDC_CLIENT_ID', 'wordpress' );\n\
define( 'OIDC_CLIENT_SECRET', '$WORDPRESS_CLIENT_SECRET' );\n\
define( 'OIDC_ENDPOINT_LOGIN_URL', 'https://authelia.$DOMAIN/api/oidc/authorization' );\n\
define( 'OIDC_ENDPOINT_USERINFO_URL', 'https://authelia.$DOMAIN/api/oidc/userinfo' );\n\
define( 'OIDC_ENDPOINT_TOKEN_URL', 'https://authelia.$DOMAIN/api/oidc/token' );\n\
define( 'OIDC_ENDPOINT_LOGOUT_URL', 'https://authelia.$DOMAIN/logout?rd=https://dashboard.$DOMAIN' );\n\
define( 'OIDC_CLIENT_SCOPE', 'openid profile email groups' );\n\
define( 'OIDC_LOGIN_TYPE', 'button' );\n\
define( 'OIDC_CREATE_IF_DOES_NOT_EXIST', '1' );\n\
define( 'OIDC_LINK_EXISTING_USERS', '1' );\n\
define( 'OIDC_REDIRECT_USER_BACK', '1' );\n\
define( 'OIDC_REDIRECT_ON_LOGOUT', '1' );\n" /federated/apps/wordpress/data/bitnami/wordpress/wp-config.php

  run_command "docker exec wordpress wp plugin install daggerhart-openid-connect-generic"
  run_command "docker exec wordpress wp plugin activate daggerhart-openid-connect-generic"

  run_command "/federated/bin/stop wordpress"
  run_command "/federated/bin/start wordpress"

  echo -ne "done.\n"
}
