#!/bin/bash -e

. ../../xi-sys.cfg

if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
    echo "Installing ModSecurity..."
    apt install libapache2-mod-security2 -y 

    echo "Adding ModSecurity Rules..."
    # Clear old rules that come with package
    rm -rf /usr/share/modsecurity-crs/rules/*
    rm -rf /etc/modsecurity/crs/*

    # Copy over rules
    cp -f ./deb_modsecurity.conf /etc/modsecurity/modsecurity.conf
    cp -f ./coreruleset-4.2.0/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf /etc/modsecurity/crs/
    cp -f ./coreruleset-4.2.0/rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf /etc/modsecurity/crs/
    cp -f ./coreruleset-4.2.0/crs-setup.conf /etc/modsecurity/crs/
    cp -f ./coreruleset-4.2.0/rules/* /usr/share/modsecurity-crs/rules/
    # Make sure these aren't duplicated
    rm -f /usr/share/modsecurity-crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
    rm -f /usr/share/modsecurity-crs/rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf

    # This version is too old to have these rules
    # https://github.com/owasp-modsecurity/ModSecurity/issues/2821
    if [ "$dist" == "ubuntu22" ]; then
        rm -f /usr/share/modsecurity-crs/rules/REQUEST-922-MULTIPART-ATTACK.conf
    fi
    #
    # TODO: What about Debian 12?
    #
    # Anything over version 2.9.6 needs this
    # https://pkgs.org/download/libapache2-mod-security2
    # https://pkgs.org/download/mod_security
    if [ "$dist" == "ubuntu24" ]; then
        file="/etc/modsecurity/modsecurity.conf"
        sed -i "s/$(grep 'SecArgumentsLimit' $file)/SecArgumentsLimit 50000/" $file 
    fi
else
    echo "Adding ModSecurity Rules..."
    # Already installed in dependencies, just need to configure rules
    rm -rf /etc/httpd/modsecurity.d/coreruleset
    mkdir -p /etc/httpd/modsecurity.d/coreruleset/rules
    mkdir -p /etc/httpd/modsecurity.d/coreruleset/plugins

    # Copy over rules
    cp -f ./rpm_modsecurity.conf /etc/httpd/conf.d/mod_security.conf
    cp -f ./coreruleset-4.2.0/crs-setup.conf /etc/httpd/modsecurity.d/coreruleset/
    cp -f ./coreruleset-4.2.0/rules/* /etc/httpd/modsecurity.d/coreruleset/rules/

fi

echo "Restarting $httpd with ModSecurity applied..."
systemctl restart $httpd 
