#!/bin/bash set -euo pipefail PLUGIN_DIR="$(cd "$(dirname "$0")/../.." && pwd)" CUSTOMBUILD_ROOT="${CUSTOMBUILD_ROOT:-/usr/local/directadmin/custombuild}" ACTION="${1:-install}" SETTINGS_FILE="${MYSQL_PLUGIN_SETTINGS_FILE:-$PLUGIN_DIR/plugin-settings.conf}" MARKER="managed by DirectAdmin MySQL plugin CustomBuild hook" log() { printf 'mysql custombuild-hooks: %s\n' "$*" } die() { printf 'mysql custombuild-hooks: %s\n' "$*" >&2 exit 1 } read_setting() { local key="$1" local default="$2" local line value [ -r "$SETTINGS_FILE" ] || { printf '%s\n' "$default" return 0 } line="$(grep -E "^${key}=" "$SETTINGS_FILE" | tail -n 1 || true)" [ -n "$line" ] || { printf '%s\n' "$default" return 0 } value="${line#*=}" value="${value%%#*}" value="${value%\"}" value="${value#\"}" value="${value%\'}" value="${value#\'}" value="$(printf '%s' "$value" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')" printf '%s\n' "${value:-$default}" } custombuild_hooks_enabled() { case "$(read_setting CUSTOMBUILD_HOOKS_ENABLED true)" in true|yes|on|1) return 0 ;; *) return 1 ;; esac } write_hook() { local target="$1" local app="$2" local repair_script="$3" local health_script="$4" local repair_name health_name tmp [ -f "$repair_script" ] || die "missing repair script: $repair_script" [ -f "$health_script" ] || die "missing health check script: $health_script" repair_name="$(basename "$repair_script")" health_name="$(basename "$health_script")" mkdir -p "$(dirname "$target")" tmp="$(mktemp)" cat > "$tmp" </dev/null || true { printf '%s\\n' "=== \$(date '+%Y-%m-%d %H:%M:%S') ${app} CustomBuild post hook ===" "\$PLUGIN_DIR/scripts/setup/${repair_name}" if ! "\$PLUGIN_DIR/scripts/setup/${health_name}"; then printf '%s\\n' "${app}: warning: health check failed after repair" fi } >> "\$LOG_FILE" 2>&1 EOF install -m 0755 "$tmp" "$target" rm -f "$tmp" log "installed CustomBuild post hook: $target" } install_all() { custombuild_hooks_enabled || { log "disabled by CUSTOMBUILD_HOOKS_ENABLED" return 0 } write_hook \ "$CUSTOMBUILD_ROOT/custom/hooks/roundcube/post/90-alt-mysql-repair.sh" \ "roundcube" \ "$PLUGIN_DIR/scripts/setup/roundcube_repair_config.sh" \ "$PLUGIN_DIR/scripts/setup/roundcube_health_check.sh" write_hook \ "$CUSTOMBUILD_ROOT/custom/hooks/phpmyadmin/post/90-alt-mysql-repair.sh" \ "phpmyadmin" \ "$PLUGIN_DIR/scripts/setup/phpmyadmin_repair.sh" \ "$PLUGIN_DIR/scripts/setup/phpmyadmin_health_check.sh" } uninstall_all() { local hook for hook in \ "$CUSTOMBUILD_ROOT/custom/hooks/roundcube/post/90-alt-mysql-repair.sh" \ "$CUSTOMBUILD_ROOT/custom/hooks/phpmyadmin/post/90-alt-mysql-repair.sh" do if [ -f "$hook" ] && grep -Fq "$MARKER" "$hook"; then rm -f "$hook" log "removed CustomBuild post hook: $hook" fi done } case "$ACTION" in install) install_all ;; uninstall) uninstall_all ;; *) die "unknown action: $ACTION" ;; esac