#!/bin/bash
#
# PowerDNS Admin Service

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

config_pdnsadmin() {
  echo -ne "* Configuring pdnsadmin container.."

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

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

networks:
  core:
    external: true
EOF

MYSQL_PASSWORD=`grep MYSQL_PASSWORD /federated/apps/pdnsmysql/.env | awk -F= '{ print $2 }'`
PDNS_APIKEY=`grep PDNS_api_key /federated/apps/pdns/.env | awk -F= '{ print $2 }'`
PDNS_ADMIN_WEBSERVER_PASSWORD_SALT=`htpasswd -bnBC 10 "" $ADMINPASS | tr -d ':\n' | sed 's/$2y/$2b/'`
PDNS_MYSQL_COMMAND="insert into user (id, username, password, firstname, lastname, email, otp_secret, role_id, confirmed) values (\"1\", \"admin@$DOMAIN\", \"$PDNS_ADMIN_WEBSERVER_PASSWORD_SALT\", \"Admin\", \"Federated\", \"admin@$DOMAIN\", \"\", \"1\", \"0\");"

cat > /federated/apps/pdnsadmin/.env <<EOF
IMAGE_VERSION="$(current_version pdnsadmin)"
PDNS_ADMIN_SQLA_DB_HOST="'mysql'"
PDNS_ADMIN_SQLA_DB_PORT="'3306'"
PDNS_ADMIN_SQLA_DB_USER="'pdns'"
PDNS_ADMIN_SQLA_DB_PASSWORD="'$MYSQL_PASSWORD'"
PDNS_ADMIN_SQLA_DB_NAME="'pdns'"
PDNS_ADMIN_SERVER_EXTERNAL_SSL=True
PDNS_API_URL="http://pdns.$DOMAIN:8081/"
PDNS_API_KEY="$PDNS_APIKEY"
PDNS_VERSION="4.9.0"
EOF
chmod 600 /federated/apps/pdnsadmin/.env

cat > /federated/apps/pdnsadmin/data/etc/uwsgi.ini <<'EOF'
[uwsgi]
strict = true
master = true
die-on-term = true
need-app = true

plugins = python3

uid = uwsgi
gid = uwsgi

chdir = /opt/powerdns-admin
pythonpath = /opt/powerdns-admin

mount = /=run.py
manage-script-name = true
callable = app

vacuum = true
harakiri = 20
buffer-size = 32768
post-buffering = 8192
protocol = http
http-socket = 0.0.0.0:9494
pidfile = /run/uwsgi/%n.pid

enable-threads = true
EOF
 
echo -ne "done.\n"
}
start_pdnsadmin() {
  # Start service with command to make sure it's up before proceeding
  start_service "pdnsadmin" "nc -z 192.168.0.12 9494 &> /dev/null" "8"

  # Run MySQL command to create admin user for pdns admin interface
  # Allowed to fail because the user may already be there from a previous start.
  docker exec pdnsmysql bash -c "mariadb -updns -p$MYSQL_PASSWORD pdns -e '$PDNS_MYSQL_COMMAND;'" || :

  echo -ne "done.\n"
}
