#!/bin/bash
#
# Baserow Service

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

config_baserow() {
  echo -ne "* Configuring baserow container.."

  if [ ! -d "/federated/apps/baserow" ]; then
    mkdir -p /federated/apps/baserow/data/baserow/data
  fi

  BASEROW_SECRET=$(create_password);

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

networks:
  core:
    external: true
EOF

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

cat > /federated/apps/baserow/.env <<EOF
IMAGE_VERSION="$(current_version baserow)"
BASEROW_PUBLIC_URL=https://baserow.$DOMAIN
DATABASE_HOST=postgresql.$DOMAIN
DATABASE_NAME=baserow
DATABASE_USER=baserow
DATABASE_PASSWORD_FILE=/baserow/data/.federated.postgresql.secret
DATABASE_PORT=5432
BASEROW_AMOUNT_OF_WORKERS=1
BASEROW_AMOUNT_OF_GUNICORN_WORKERS=1
BASEROW_RUN_MINIMAL=1
BASEROW_TRIGGER_SYNC_TEMPLATES_AFTER_MIGRATION=true
EMAIL_SMTP=True
FROM_EMAIL=baserow@$DOMAIN
EMAIL_SMTP_HOST=mail.$DOMAIN
EMAIL_SMTP_PORT=587
EMAIL_SMTP_USER=$SMTPUSER
EMAIL_SMTP_PASSWORD=$ADMINPASS
EMAIL_SMTP_USE_TLS=True
EOF
chmod 600 /federated/apps/baserow/.env

echo "$BASEROW_SECRET" > /federated/apps/baserow/data/baserow/data/.federated.postgresql.secret

cat > /federated/apps/baserow/data/createuser.sh <<EOF
#!/bin/bash

curl -X POST -H 'Content-Type: application/json' -i http://localhost/api/user/ --data '{
"name": "admin",
"email": "admin@$DOMAIN",
"password": "$ADMINPASS"
}' &> /dev/null
EOF
chmod +x /federated/apps/baserow/data/createuser.sh

# Create database and user in postgresql
docker exec postgresql psql -U postgres -c "CREATE USER baserow WITH PASSWORD '$BASEROW_SECRET'" &> /dev/null
docker exec postgresql psql -U postgres -c "CREATE DATABASE baserow" &> /dev/null
docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE baserow TO baserow" &> /dev/null
 
echo -ne "done.\n"
}
email_baserow() {
  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>Listmonk 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">Baserow</td>
    <td class="tg-kwiq"><a href="https://baserow.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">baserow.$DOMAIN</span></a></td>
    <td class="tg-kwiq">admin@$DOMAIN<br>admin password above</td>
    <td class="tg-kwiq">User access is separate from panel. Use the admin account to login and then invite other users</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">Baserow (Air table replacement) allows you to create and customize databases without writing any code</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_baserow() {
  echo -ne "* Uninstalling baserow container.."

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

  # Delete database and user in postgresql
  docker exec postgresql psql -U postgres -c "DROP DATABASE baserow" &> /dev/null
  docker exec postgresql psql -U postgres -c "DROP USER baserow" &> /dev/null

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

  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil delete-rrset $DOMAIN baserow A &> /dev/null

  echo -ne "done.\n"
}
start_baserow() {
  # Start service with command to make sure it's up before proceeding
  start_service "baserow" "docker exec baserow curl http://localhost:8000 &> /dev/null" "20"

  # Move createuser.sh and set it executable
  mv /federated/apps/baserow/data/createuser.sh /federated/apps/baserow/data/baserow/data/
  docker exec baserow chmod 755 /baserow/data/createuser.sh
  [ $? -ne 0 ] && fail "Couldn't chown createuser.sh in /federated/apps/baserow container"

  # Run createuser.sh inside baserow container
  docker exec baserow /baserow/data/createuser.sh
  [ $? -ne 0 ] && fail "Couldn't run createuser.sh in /federated/apps/baserow container"

  # Disable new sign ups
  docker exec postgresql psql -U baserow -c "update core_settings set allow_new_signups='f' where allow_new_signups='t';"

  # Remove baserow create user
  rm /federated/apps/baserow/data/baserow/data/createuser.sh

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

  echo -ne "done."
}
