#!/usr/bin/env bash
# ONOXSOFT Autodiscover endpoint installer
#
# Copies autodiscover.xml.php and thunderbird.xml.php to
# /usr/local/onoxsoft/autodiscover/ and chowns them apache:apache.
#
# Called by install.sh during panel setup (after Apache + mail stack).
#
# Idempotent: re-runs are safe.

set -euo pipefail

readonly TARGET_DIR="/usr/local/onoxsoft/autodiscover"
readonly SRC_DIR="$(dirname "$(readlink -f "$0")")"

# Detect web user (Apache: 'apache' on RHEL, 'www-data' on Debian/Ubuntu)
WEB_USER="apache"
if id www-data >/dev/null 2>&1; then
    WEB_USER="www-data"
fi

echo "[autodiscover] installing endpoint to ${TARGET_DIR}"

install -d -m 0755 -o "${WEB_USER}" -g "${WEB_USER}" "${TARGET_DIR}"

# Copy PHP endpoint scripts
install -m 0644 -o "${WEB_USER}" -g "${WEB_USER}" \
    "${SRC_DIR}/autodiscover.xml.php" \
    "${TARGET_DIR}/autodiscover.xml.php"

install -m 0644 -o "${WEB_USER}" -g "${WEB_USER}" \
    "${SRC_DIR}/thunderbird.xml.php" \
    "${TARGET_DIR}/thunderbird.xml.php"

# Drop a .htaccess that denies everything except the two PHP files (defense-in-depth)
cat > "${TARGET_DIR}/.htaccess" <<'HTACCESS'
# ONOXSOFT autodiscover — only allow the two endpoint scripts
<FilesMatch "\.(xml\.php)$">
    Require all granted
</FilesMatch>
<Files "*">
    Require all denied
</Files>
<Files "autodiscover.xml.php">
    Require all granted
</Files>
<Files "thunderbird.xml.php">
    Require all granted
</Files>
HTACCESS

chown "${WEB_USER}:${WEB_USER}" "${TARGET_DIR}/.htaccess"
chmod 0644 "${TARGET_DIR}/.htaccess"

# Optional: write a default mail config if /etc/onoxsoft/mail.conf doesn't exist.
# The panel later updates this on mail-stack provision.
if [[ ! -f /etc/onoxsoft/mail.conf ]]; then
    install -d -m 0755 /etc/onoxsoft
    cat > /etc/onoxsoft/mail.conf <<'CONF'
# ONOXSOFT mail server config (consumed by autodiscover endpoints)
# Lines: key=value (parse_ini_file format)
hostname=mail.localhost
imap_port=993
smtp_port=587
CONF
    chmod 0644 /etc/onoxsoft/mail.conf
fi

echo "[autodiscover] installed:"
ls -la "${TARGET_DIR}"
