#!/usr/bin/env bash

# Copyright (c) 2021-2026 community-scripts ORG
# Author: Slaviša Arežina (tremor021)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://www.powerdns.com/

source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os

msg_info "Installing Dependencies"
$STD apt install -y sqlite3
msg_ok "Installed Dependencies"

PHP_VERSION="8.3" PHP_APACHE="YES" PHP_FPM="YES" PHP_MODULE="gettext,tokenizer,sqlite3,ldap" setup_php
setup_deb822_repo \
  "pdns" \
  "https://repo.powerdns.com/FD380FBB-pub.asc" \
  "http://repo.powerdns.com/debian" \
  "trixie-auth-50"

cat <<EOF >/etc/apt/preferences.d/auth-50
Package: pdns-*
Pin: origin repo.powerdns.com
Pin-Priority: 600
EOF

escape_sql() {
  printf '%s' "$1" | sed "s/'/''/g"
}

msg_info "Setting up PowerDNS"
$STD apt install -y \
  pdns-server \
  pdns-backend-sqlite3
sed -i 's/^launch=$/# launch=/' /etc/powerdns/pdns.conf
rm -f /etc/powerdns/pdns.d/bind.conf
cat <<EOF >/etc/powerdns/pdns.d/gsqlite3.conf
launch=gsqlite3
gsqlite3-database=/opt/poweradmin/powerdns.db
EOF
msg_ok "Setup PowerDNS"

fetch_and_deploy_gh_release "poweradmin" "poweradmin/poweradmin" "tarball"

msg_info "Setting up Poweradmin"
sqlite3 /opt/poweradmin/powerdns.db </opt/poweradmin/sql/poweradmin-sqlite-db-structure.sql
sqlite3 /opt/poweradmin/powerdns.db </opt/poweradmin/sql/pdns/49/schema.sqlite3.sql
PA_ADMIN_USERNAME="admin"
PA_ADMIN_EMAIL="admin@example.com"
PA_ADMIN_FULLNAME="Administrator"
PA_ADMIN_PASSWORD=$(openssl rand -base64 16 | tr -d "=+/" | cut -c1-16)
PA_SESSION_KEY=$(openssl rand -base64 75 | tr -dc 'A-Za-z0-9^@#!(){}[]%_\-+=~' | head -c 50)
PASSWORD_HASH=$(php -r "echo password_hash(\$argv[1], PASSWORD_DEFAULT);" -- "${PA_ADMIN_PASSWORD}" 2>/dev/null)
sqlite3 /opt/poweradmin/powerdns.db "INSERT INTO users (username, password, fullname, email, description, perm_templ, active, use_ldap) \
  VALUES ('$(escape_sql "${PA_ADMIN_USERNAME}")', '$(escape_sql "${PASSWORD_HASH}")', '$(escape_sql "${PA_ADMIN_FULLNAME}")', \
  '$(escape_sql "${PA_ADMIN_EMAIL}")', 'System Administrator', 1, 1, 0);"

cat <<EOF >~/poweradmin.creds
Admin Username: ${PA_ADMIN_USERNAME}
Admin Password: ${PA_ADMIN_PASSWORD}
EOF

cat <<EOF >/opt/poweradmin/config/settings.php
<?php

/**
 * Poweradmin Settings Configuration File
 *
 * Generated by the installer on 2026-02-02 21:01:40
 */

return [
    /**
     * Database Settings
     */
    'database' => [
        'type' => 'sqlite',
        'file' => '/opt/poweradmin/powerdns.db',
    ],

    /**
     * Security Settings
     */
    'security' => [
        'session_key' => '${PA_SESSION_KEY}',
    ],

    /**
     * Interface Settings
     */
    'interface' => [
        'language' => 'en_EN',
    ],

    /**
     * DNS Settings
     */
    'dns' => [
        'hostmaster' => 'localhost.lan',
        'ns1' => '8.8.8.8',
        'ns2' => '9.9.9.9',
    ]
];
EOF
rm -rf /opt/poweradmin/install
msg_ok "Setup Poweradmin"

msg_info "Creating Service"
rm /etc/apache2/sites-enabled/000-default.conf
cat <<EOF >/etc/apache2/sites-enabled/poweradmin.conf
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot /opt/poweradmin

    <Directory /opt/poweradmin>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # For DDNS update functionality
    RewriteEngine On
    RewriteRule ^/update(.*)\$ /dynamic_update.php [L]
    RewriteRule ^/nic/update(.*)\$ /dynamic_update.php [L]
</VirtualHost>
EOF
$STD a2enmod rewrite headers
chown -R www-data:pdns /opt/poweradmin
chmod 775 /opt/poweradmin
chown pdns:pdns /opt/poweradmin/powerdns.db
chmod 664 /opt/poweradmin/powerdns.db
usermod -aG pdns www-data
$STD systemctl restart pdns apache2
msg_ok "Created Service"

motd_ssh
customize
cleanup_lxc
