#!/bin/bash
#
# EspoCRM Service

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

config_espocrm() {
  echo -ne "* Configuring espocrm container.."

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

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

networks:
  core:
    external: true
EOF

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

cat > /federated/apps/espocrm/.env <<EOF
IMAGE_VERSION="$(current_version espocrm)"
ESPOCRM_DATABASE_HOST=pdnsmysql.$DOMAIN
ESPOCRM_DATABASE_NAME=espocrm
ESPOCRM_DATABASE_USER=espocrm
ESPOCRM_DATABASE_PASSWORD=$ESPOCRM_SECRET
ESPOCRM_ADMIN_USERNAME=admin@$DOMAIN
ESPOCRM_ADMIN_PASSWORD=$ADMINPASS
ESPOCRM_CONFIG_SMTP_PORT=587
ESPOCRM_CONFIG_SMTP_AUTH=true
ESPOCRM_CONFIG_SMTP_SECURITY=TLS
ESPOCRM_CONFIG_SMTP_USERNAME=$SMTPUSER
ESPOCRM_CONFIG_SMTP_PASSWORD=$ADMINPASS
ESPOCRM_CONFIG_SMTP_SERVER=mail.$DOMAIN
ESPOCRM_CONFIG_OUTBOUND_EMAIL_FROM_ADDRESS=espocrm@$DOMAIN
ESPOCRM_CONFIG_AUTHENTICATION_METHOD=LDAP
ESPOCRM_CONFIG_LDAP_USER_NAME_ATTRIBUTE=mail
ESPOCRM_CONFIG_LDAP_USER_FIRST_NAME_ATTRIBUTE=givenName
ESPOCRM_CONFIG_LDAP_USER_LAST_NAME_ATTRIBUTE=sn
ESPOCRM_CONFIG_LDAP_USER_TITLE_ATTRIBUTE=cn
ESPOCRM_CONFIG_LDAP_USER_EMAIL_ADDRESS_ATTRIBUTE=mail
ESPOCRM_CONFIG_LDAP_USER_PHONE_NUMBER_ATTRIBUTE=cn
ESPOCRM_CONFIG_LDAP_USER_OBJECT_CLASS=inetOrgPerson
ESPOCRM_CONFIG_LDAP_HOST=ldap.$DOMAIN
ESPOCRM_CONFIG_LDAP_PORT=636
ESPOCRM_CONFIG_LDAP_SECURITY=SSL
ESPOCRM_CONFIG_LDAP_AUTH=true
ESPOCRM_CONFIG_LDAP_USERNAME=cn=admin,dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST
ESPOCRM_CONFIG_LDAP_PASSWORD=$LDAP_SECRET
ESPOCRM_CONFIG_LDAP_ACCOUNT_CANONICAL_FORM=Dn
ESPOCRM_CONFIG_LDAP_BASE_DN=dc=$LDAP_DOMAIN_FIRST,dc=$LDAP_DOMAIN_LAST
ESPOCRM_CONFIG_LDAP_BIND_REQUIRES_DN=true
ESPOCRM_CONFIG_LDAP_CREATE_ESPO_USER=true
ESPOCRM_CONFIG_LDAP_PORTAL_USER_LDAP_AUTH=true
ESPOCRM_SITE_URL="https://espocrm.$DOMAIN"
EOF
chmod 600 /federated/apps/espocrm/.env

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

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

  # Install cronjob
  (crontab -l 2>/dev/null; echo "* * * * * /usr/bin/docker exec espocrm /usr/local/bin/php -f /var/www/html/cron.php > /dev/null 2>&1") | sort -u | crontab -

  echo -ne "done.\n"
}
email_espocrm() {
  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>EspoCRM is now installed on $DOMAIN</h4>
<p>
Here is your applications chart 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}
.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-0pky">EspoCRM</td>
    <td class="tg-0pky"><a href="https://espocrm.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">espocrm.$DOMAIN</span></a></td>
    <td class="tg-0pky">admin@$DOMAIN<br>your admin password</td>
    <td class="tg-0pky">All users in panel can access EspoCRM using user@$DOMAIN</td>
    <td class="tg-cul6"><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-0pky">EspoCRM is an Open Source CRM (Customer Relationship Management) software that allows you to see, enter and evaluate all your company relationships</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_espocrm() {
  echo -ne "* Uninstalling espocrm container.."

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

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

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

  # Delete the image
  docker image rm espocrm/espocrm:${IMAGE_VERSION} &> /dev/null

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

  # Remove cronjob
  crontab -l | grep -v 'espocrm /usr/local/bin/php -f /var/www/html/cron.php'  | crontab -

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

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

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
     ### Espocrm
      - client_id: 'espocrm'
        client_name: 'Espocrm'
        client_secret: $ESPOCRM_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - 'https://espocrm.$DOMAIN/oauth-callback.php'
        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"

cat >> /federated/apps/espocrm/.env <<EOF
ESPOCRM_CONFIG_AUTHENTICATION_METHOD=Oidc
ESPOCRM_CONFIG_OIDC_USERNAME_CLAIM=preferred_username
ESPOCRM_CONFIG_OIDC_FALLBACK=true
ESPOCRM_CONFIG_OIDC_CLIENT_ID=espocrm
ESPOCRM_CONFIG_OIDC_CLIENT_SECRET=$ESPOCRM_CLIENT_SECRET
ESPOCRM_CONFIG_OIDC_AUTHORIZATION_ENDPOINT=https://authelia.$DOMAIN/api/oidc/authorization
ESPOCRM_CONFIG_OIDC_TOKEN_ENDPOINT=https://authelia.$DOMAIN/api/oidc/token
ESPOCRM_CONFIG_OIDC_JWKS_ENDPOINT=https://authelia.$DOMAIN/jwks.json
ESPOCRM_CONFIG_OIDC_LOGOUT_URL=https://authelia.$DOMAIN/logout?rd=https://dashboard.$DOMAIN
ESPOCRM_CONFIG_OIDC_CREATE_USER=true
ESPOCRM_CONFIG_OIDC_ALLOW_ADMIN_USER=true
ESPOCRM_CONFIG_OIDC_SYNC=false
ESPOCRM_CONFIG_OIDC_SYNC_TEAMS=false
ESPOCRM_CONFIG_OIDC_ALLOW_REGULAR_USER_FALLBACK=false
ESPOCRM_CONFIG_OIDC_AUTHORIZATION_PROMPT=consent
EOF

  # Add in Scopes after authenticationMethod
  sed -i "/oidcScopes/{n;N;N;N;d}" /federated/apps/espocrm/data/var/www/html/data/config.php
  sed -i "/oidcScopes/d" /federated/apps/espocrm/data/var/www/html/data/config.php
  sed -i "/authenticationMethod/a  \  'oidcScopes' => [\n\    0 => 'profile',\n\    1 => 'email',\n\    2 => 'groups',\n\    3 => 'openid'\n\  ]," /federated/apps/espocrm/data/var/www/html/data/config.php

  # Add in extra_hosts to docker-compose
  add_authelia_config_to_dockercompose "espocrm" "$EXTERNALIP"

  # Set auth method to Oidc only
  sed -i "s/ESPOCRM_CONFIG_AUTHENTICATION_METHOD=LDAP/#ESPOCRM_CONFIG_AUTHENTICATION_METHOD=LDAP/g" /federated/apps/espocrm/.env

  run_command "/federated/bin/stop espocrm"
  run_command "/federated/bin/start espocrm"

  echo -ne "done.\n"
  fi
}
configsso_espocrm_plus() {
  ESPOCRM_CLIENT_SECRET=$(cat /federated/apps/espocrm/.espocrm.client.secret)

cat >> /federated/apps/espocrm/.env <<EOF
ESPOCRM_CONFIG_AUTHENTICATION_METHOD=Oidc
ESPOCRM_CONFIG_OIDC_USERNAME_CLAIM=preferred_username
ESPOCRM_CONFIG_OIDC_FALLBACK=true
ESPOCRM_CONFIG_OIDC_CLIENT_ID=espocrm
ESPOCRM_CONFIG_OIDC_CLIENT_SECRET=$ESPOCRM_CLIENT_SECRET
ESPOCRM_CONFIG_OIDC_AUTHORIZATION_ENDPOINT=https://authelia.$DOMAIN/api/oidc/authorization
ESPOCRM_CONFIG_OIDC_TOKEN_ENDPOINT=https://authelia.$DOMAIN/api/oidc/token
ESPOCRM_CONFIG_OIDC_JWKS_ENDPOINT=https://authelia.$DOMAIN/jwks.json
ESPOCRM_CONFIG_OIDC_LOGOUT_URL=https://authelia.$DOMAIN/logout?rd=https://dashboard.$DOMAIN
ESPOCRM_CONFIG_OIDC_CREATE_USER=true
ESPOCRM_CONFIG_OIDC_ALLOW_ADMIN_USER=true
ESPOCRM_CONFIG_OIDC_SYNC=false
ESPOCRM_CONFIG_OIDC_SYNC_TEAMS=false
ESPOCRM_CONFIG_OIDC_ALLOW_REGULAR_USER_FALLBACK=false
ESPOCRM_CONFIG_OIDC_AUTHORIZATION_PROMPT=consent
EOF

  # Add in Scopes after authenticationMethod
  sed -i "/oidcScopes/{n;N;N;N;d}" /federated/apps/espocrm/data/var/www/html/data/config.php
  sed -i "/oidcScopes/d" /federated/apps/espocrm/data/var/www/html/data/config.php
  sed -i "/authenticationMethod/a  \  'oidcScopes' => [\n\    0 => 'profile',\n\    1 => 'email',\n\    2 => 'groups',\n\    3 => 'openid'\n\  ]," /federated/apps/espocrm/data/var/www/html/data/config.php

  # Set auth method to Oidc only
  sed -i "s/ESPOCRM_CONFIG_AUTHENTICATION_METHOD=LDAP/#ESPOCRM_CONFIG_AUTHENTICATION_METHOD=LDAP/g" /federated/apps/espocrm/.env

  run_command "/federated/bin/stop espocrm"
  run_command "/federated/bin/start espocrm"
}
