#!/bin/bash
#
# EspoCRM Service

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

config_espocrm() {
  echo -ne "\n* Configuring espocrm container.."
  spin &
  SPINPID=$!

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

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

services:
  espocrm:
    image: espocrm/espocrm:\${IMAGE_VERSION}
    container_name: espocrm
    hostname: espocrm.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.39
    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:
  federated:
    external: true
EOF

ADMINPASS=`cat /federated/apps/panel/.env | grep SMTP_PASSWORD | awk -F= '{ print $2 }'`
EXTERNALIP=$(get_externalip);
ESPOCRM_SECRET=$(create_password);
MYSQL_ROOTPASSWORD=`cat /federated/apps/pdnsmysql/.env | grep MYSQL_ROOT_PASSWORD | awk -F= '{ print $2 }'`
LDAP_SECRET=`cat /federated/apps/ldap/.ldap.secret`
# Set SMTP user based on if fcore exists
[[ $(docker exec ldap slapcat | grep fcore) ]] && SMTPUSER="fcore" || SMTPUSER="admin"

cat > /federated/apps/espocrm/.env <<EOF
IMAGE_VERSION="8.0.5-apache"
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=federatedcomputer,dc=cloud
ESPOCRM_CONFIG_LDAP_PASSWORD=$LDAP_SECRET
ESPOCRM_CONFIG_LDAP_ACCOUNT_CANONICAL_FORM=Dn
ESPOCRM_CONFIG_LDAP_BASE_DN=dc=federatedcomputer,dc=cloud
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 "mysql -uroot -p$MYSQL_ROOTPASSWORD -e 'create database espocrm;'"
docker exec pdnsmysql bash -c "mysql -uroot -p$MYSQL_ROOTPASSWORD -e \"CREATE USER 'espocrm'@'%' IDENTIFIED BY '$ESPOCRM_SECRET';\""
docker exec pdnsmysql bash -c "mysql -uroot -p$MYSQL_ROOTPASSWORD -e \"grant all privileges on espocrm.* to 'espocrm'@'%';\""
docker exec pdnsmysql bash -c "mysql -uroot -p$MYSQL_ROOTPASSWORD -e 'flush privileges;'"
 
kill -9 $SPINPID &> /dev/null
echo -ne "done.\n"
}
start_espocrm() {
  # Start service with command to make sure it's up before proceeding
  start_service "espocrm" "nc -z 172.99.0.39 80 &> /dev/null" "7"

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

  # 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 -

  kill -9 $SPINPID &> /dev/null
  echo -ne "done.\n"
}
email_espocrm() {
  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>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

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

  # 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 "mysql -uroot -p$MYSQL_ROOTPASSWORD -e 'drop database espocrm;'" &> /dev/null
  docker exec pdnsmysql bash -c "mysql -uroot -p$MYSQL_ROOTPASSWORD -e 'drop user espocrm;'" &> /dev/null

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

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