#!/bin/bash
set -e

PROJ_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PROJ_DIR"

echo "============================================"
echo "  DMARC Setup  "
echo "============================================"
echo ""

# DKIM key pairs generation (1024-bit RSA)
for DOMAIN in legit.lab thirdparty.lab misconf.lab; do
    KEY_DIR="sender-mta/keys/${DOMAIN}"
    mkdir -p "$KEY_DIR"

    if [ -f "$KEY_DIR/selector1.private" ]; then
        echo "DKIM key for ${DOMAIN} already exists - skipping"
    else
        echo "Generating DKIM key pair for ${DOMAIN} ..."
        openssl genrsa -out "$KEY_DIR/selector1.private" 1024 2>/dev/null
        openssl rsa -in "$KEY_DIR/selector1.private" \
            -pubout -outform DER 2>/dev/null | base64 -w 0 \
            > "$KEY_DIR/selector1.pub"
        echo "--> private: $KEY_DIR/selector1.private"
        echo "--> public:  $KEY_DIR/selector1.pub"
    fi
done

# Build DNS zone files from templates
echo ""
echo "Generating DNS zone files from templates ..."

LEGIT_PUB=$(cat sender-mta/keys/legit.lab/selector1.pub)
THIRD_PUB=$(cat sender-mta/keys/thirdparty.lab/selector1.pub)

sed "s|__DKIM_PUBKEY__|${LEGIT_PUB}|g" \
    dns/zones/legit.lab.zone.template > dns/zones/legit.lab.zone
echo "--> dns/zones/legit.lab.zone"

sed "s|__DKIM_PUBKEY__|${THIRD_PUB}|g" \
    dns/zones/thirdparty.lab.zone.template > dns/zones/thirdparty.lab.zone
echo "--> dns/zones/thirdparty.lab.zone"

MISCONF_PUB=$(cat sender-mta/keys/misconf.lab/selector1.pub)
sed "s|__DKIM_PUBKEY__|${MISCONF_PUB}|g" \
    dns/zones/misconf.lab.zone.template > dns/zones/misconf.lab.zone
echo "--> dns/zones/misconf.lab.zone"

echo ""
echo "---------------------------------------------"
echo "  Setup complete!  Next steps:"
echo ""
echo "    docker compose up --build -d"
echo "    sleep 15            # wait for services"
echo "    docker compose exec sender-mta bash /scripts/scenario-a.sh"
echo "    docker compose exec sender-mta bash /scripts/scenario-b.sh"
echo "    docker compose exec sender-mta bash /scripts/scenario-c.sh"
echo "    docker compose exec sender-mta bash /scripts/scenario-d.sh"
echo "---------------------------------------------"
