#!/bin/bash

# Script to automatically update TLSA records when certificates are renewed.
# This should be triggered by certdumper or Traefik certificate renewal.

set -e

# Configuration.
mailcowHostname="${MAILCOW_HOSTNAME:-mail.nasarek.dev}"
domain="${DOMAIN:-nasarek.dev}"
dnsApiKey="${DNS_API_KEY:-}"
dnsApiPassword="${DNS_API_PASSWORD:-}"
dnsCustomerNumber="${DNS_CUSTOMER_NUMBER:-}"

# Paths.
certFile="/var/deploy/mailcow/data/assets/ssl/cert.pem"
logFile="/var/deploy/scripts/tlsa-update.log"

# Logging function.
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$logFile"
}

# Check if certificate file exists.
if [ ! -f "$certFile" ]; then
  log "ERROR: Certificate file not found: $certFile"
  exit 1
fi

# Generate TLSA hash from certificate.
generateTlsaHash() {
  local certPath="$1"
  if [ ! -f "$certPath" ]; then
    log "ERROR: Certificate file not found: $certPath"
    return 1
  fi

  openssl x509 -in "$certPath" -noout -pubkey | \
    openssl pkey -pubin -outform der | \
    openssl dgst -sha256 | \
    awk '{print $2}'
}

# Update TLSA record via DNS provider API.
updateTlsaRecord() {
  local port="$1"
  local hash="$2"
  local recordName="_${port}._tcp.${mailcowHostname}"

  log "Updating TLSA record: ${recordName}"

  # Check if DNS provider API credentials are configured.
  if [ -z "$dnsApiKey" ] || [ -z "$dnsApiPassword" ] || [ -z "$dnsCustomerNumber" ]; then
    log "WARNING: DNS provider API credentials not configured. TLSA record needs manual update:"
    log "  ${recordName} TLSA 3 1 1 ${hash}"
    return 1
  fi

  # DNS provider API call would go here.
  # For now, we'll log the required values.
  log "INFO: Use DNS provider API to update:"
  log "  Record: ${recordName}"
  log "  Type: TLSA"
  log "  Value: 3 1 1 ${hash}"

  # TODO: Implement DNS provider API call.
  # Example for Netcup:
  # curl -X POST https://ccp.netcup.net/run/webservice/servers/endpoint.php \
  #   -d "apikey=${dnsApiKey}&apipassword=${dnsApiPassword}&customernumber=${dnsCustomerNumber}&domainname=${domain}&dnsrecordset=..."
}

# Main execution.
main() {
  log "Starting TLSA record update check..."

  # Generate hash from current certificate.
  local tlsaHash
  tlsaHash=$(generateTlsaHash "$certFile")

  if [ -z "$tlsaHash" ]; then
    log "ERROR: Failed to generate TLSA hash"
    exit 1
  fi

  log "Generated TLSA hash: ${tlsaHash}"

  # Update TLSA records for all mail ports.
  updateTlsaRecord "25" "$tlsaHash"
  updateTlsaRecord "465" "$tlsaHash"
  updateTlsaRecord "587" "$tlsaHash"

  log "TLSA update check completed"
}

main "$@"
