#!/bin/bash

# === CONFIGURATION ===
VENDOR_ID="hostinggroup"
MODSEC_VERSION="2.9.10"
DIST_URL="https://modsec.hostinggroup.dk"
VENDOR_FOLDER="./$VENDOR_ID"
ZIP_FILE="$VENDOR_ID.zip"
YAML_FILE="meta_${VENDOR_ID}.yaml"
REMOTE_HOST="modsec.hostinggroup.dk"
REMOTE_PATH="/var/www/modsec"
REVISION_FILE=".revision"

# === LOAD OR CREATE REVISION ===
if [ -f "$REVISION_FILE" ]; then
  REVISION=$(cat "$REVISION_FILE")
  NEW_REVISION=$((REVISION + 1))
else
  NEW_REVISION=1
fi
echo "$NEW_REVISION" > "$REVISION_FILE"

DIST_NAME="${VENDOR_ID}-${NEW_REVISION}"

# === ZIP THE RULES DIRECTORY ===
echo "[+] Zipping rules directory: $VENDOR_FOLDER → $ZIP_FILE"
rm -f "$ZIP_FILE"
zip -rq "$ZIP_FILE" "$VENDOR_FOLDER"

if [ $? -ne 0 ]; then
  echo "[!] Failed to zip rules directory."
  exit 1
fi

# === GENERATE CHECKSUMS ===
MD5=$(md5sum "$ZIP_FILE" | awk '{ print $1 }')
SHA512=$(sha512sum "$ZIP_FILE" | awk '{ print $1 }')

# === GENERATE YAML FILE ===
echo "[+] Generating YAML file: $YAML_FILE (Revision: $NEW_REVISION)"

cat > "$YAML_FILE" <<EOF
$MODSEC_VERSION:
  MD5: "$MD5"
  SHA512: "$SHA512"
  distribution: $DIST_NAME
  url: $DIST_URL/$ZIP_FILE

attributes:
  description: 'Custom ModSecurity rules from HostingGroup for enhanced web hosting protection.'
  name: 'HostingGroup ModSecurity Rules'
  vendor_url: https://hostinggroup.dk
  report_url: https://modsec.hostinggroup.dk/report.html
EOF

# === VERIFY FILES EXIST ===
if [ ! -f "$ZIP_FILE" ] || [ ! -f "$YAML_FILE" ]; then
  echo "[!] Missing generated files. Exiting."
  exit 1
fi

echo "[✔] Update complete. New distribution: $DIST_NAME"
