#!/bin/bash
#
# Castopod Service

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

config_castopod() {
  echo -ne "* Configuring castopod container.."

  if [ ! -d "/federated/apps/castopod" ]; then
    mkdir -p /federated/apps/castopod/data/var/www/castopod/public/media
    chown -R 33 /federated/apps/castopod/data/var
  fi

cat > /federated/apps/castopod/docker-compose.yml <<EOF
services:
  castopod:
    image: castopod/castopod:\${IMAGE_VERSION}
    container_name: castopod
    hostname: castopod.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.33
    volumes:
      - ./data/var/www/castopod/public/media:/var/www/castopod/public/media
    env_file:
      - ./.env
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.castopod.rule=Host(\`castopod.$DOMAIN\`) || Host(\`podcasts.$DOMAIN\`)"
      - "traefik.http.routers.castopod.entrypoints=websecure"
      - "traefik.http.routers.castopod.tls.certresolver=letsencrypt"
      - "traefik.http.services.castopod.loadbalancer.server.port=8000"

networks:
  core:
    external: true
EOF

CP_ANALYTICS_SALT=$(create_password)
CASTOPOD_SECRET=$(create_password)

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

cat > /federated/apps/castopod/.env <<EOF
IMAGE_VERSION="$(current_version castopod)"
MYSQL_DATABASE=castopod
MYSQL_USER=castopod
MYSQL_PASSWORD=$CASTOPOD_SECRET
CP_DATABASE_HOSTNAME=pdnsmysql.$DOMAIN
CP_BASEURL="https://castopod.$DOMAIN"
CP_ANALYTICS_SALT="$CP_ANALYTICS_SALT"
CP_EMAIL_SMTP_HOST="mail.$DOMAIN"
CP_EMAIL_FROM="castopod@$DOMAIN"
CP_EMAIL_SMTP_USERNAME="fcore"
CP_EMAIL_SMTP_PASSWORD=$ADMINPASS
CP_EMAIL_SMTP_PORT="587"
CP_EMAIL_SMTP_CRYPTO="tls"
EOF
chmod 600 /federated/apps/castopod/.env

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

  CASTOPOD_BASE_URL="https://castopod.$DOMAIN"
  CASTOPOD_ADMIN_USERNAME="admin@$DOMAIN"
  CASTOPOD_ADMIN_EMAIL="admin@$DOMAIN"
  CASTOPOD_ADMIN_PASSWORD="$ADMINPASS"

  if [[ "${PLUS}" != "true" ]]; then
    CSRF_TEST_NAME=$(curl -v -k -c /tmp/cp-cookies $CASTOPOD_BASE_URL/cp-install | sed -n 's/.*input.*name="csrf_test_name".*value="\([^"]\+\)".*/\1/p') &> /dev/null
    curl -v -b /tmp/cp-cookies --data-urlencode "csrf_test_name=$CSRF_TEST_NAME" --data-urlencode "username=$CASTOPOD_ADMIN_USERNAME" --data-urlencode "email=$CASTOPOD_ADMIN_EMAIL" --data-urlencode "password=$CASTOPOD_ADMIN_PASSWORD" $CASTOPOD_BASE_URL/cp-install/create-superadmin &> /dev/null
    rm /tmp/cp-cookies
  else
    sleep 30
    CSRF_TEST_NAME=$(curl -v -k -c /tmp/cp-cookies $CASTOPOD_BASE_URL/cp-install | sed -n 's/.*input.*name="csrf_test_name".*value="\([^"]\+\)".*/\1/p') &> /dev/null
    curl -v -b /tmp/cp-cookies --data-urlencode "csrf_test_name=$CSRF_TEST_NAME" --data-urlencode "username=$CASTOPOD_ADMIN_USERNAME" --data-urlencode "email=$CASTOPOD_ADMIN_EMAIL" --data-urlencode "password=$CASTOPOD_ADMIN_PASSWORD" $CASTOPOD_BASE_URL/cp-install/create-superadmin &> /dev/null
    rm /tmp/cp-cookies
  fi

  if [[ "${PLUS}" != "true" ]]; then
    docker exec pdns pdnsutil add-record $DOMAIN castopod A 86400 $EXTERNALIP &> /dev/null
    docker exec pdns pdnsutil add-record $DOMAIN podcasts A 86400 $EXTERNALIP &> /dev/null
  fi

  echo -ne "done."
}
email_castopod() {
  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>Castopod 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">Castopod</td>
    <td class="tg-kwiq"><a href="https://castopod.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">castopod.$DOMAIN/cp-auth/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">Castopod is a full platform for hosting and delivering podcasts to your audience</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_castopod() {
  echo -ne "* Uninstalling castopod container.."

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

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

  docker exec pdns pdnsutil delete-rrset $DOMAIN castopod A
  docker exec pdns pdnsutil delete-rrset $DOMAIN podcasts A

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

  echo -ne "done.\n"
}
