#!/bin/bash

# Monitor certificate file and update TLSA records when it changes.
# This script checks the certificate modification time and updates TLSA if changed.

set -e

# Configuration.
certFile="/var/deploy/mailcow/data/assets/ssl/cert.pem"
stateFile="/var/deploy/scripts/.tlsa-state"
updateScript="/var/deploy/scripts/update-tlsa.sh"

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

# Get certificate modification time and hash.
currentMtime=$(stat -c %Y "$certFile" 2>/dev/null || stat -f %m "$certFile" 2>/dev/null)
currentHash=$(openssl x509 -in "$certFile" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':')

# Read previous state.
if [ -f "$stateFile" ]; then
  # shellcheck source=/dev/null
  source "$stateFile"
else
  previousMtime=0
  previousHash=""
fi

# Check if certificate has changed.
if [ "$currentMtime" != "$previousMtime" ] || [ "$currentHash" != "$previousHash" ]; then
  echo "Certificate changed detected. Updating TLSA records..."

  # Run update script.
  if [ -x "$updateScript" ]; then
    "$updateScript"
  else
    echo "ERROR: Update script not found or not executable: $updateScript"
    exit 1
  fi

  # Save new state.
  cat > "$stateFile" <<EOF
previousMtime=$currentMtime
previousHash=$currentHash
EOF

  echo "TLSA records updated successfully"
else
  echo "No certificate changes detected"
fi
