#!/bin/bash
find_suspicious_posts() {
    name="${1?Must include host and document root to check}"
    document_root="${2?Missing either hostname or document root}"

    domlog="/usr/local/apache/domlogs/${name}"

    [[ -f "$domlog" ]] || continue

    cat "$domlog" |
        awk '$6~/POST/&&
            $11~"\"-\""&&
            $7!~/(cron|xmlrpc.php|wp-login.php|admin-ajax.php)$/&&
            $9~/^2/{if (!x[$7]++)
            {print $7}}' \
            | (

                while read url; do
                    file="${document_root}${url}"
                    [[ -f "$file" ]] && echo "$file"
                done
        )

}

search_one_domain() {
    domain="${1}"
    awk -v domain="$domain" \
        '/ServerName/{name=$2}
        /Server(Name|Alias)/&&$0~"\\y"domain"\\y"{v=1}
        v&&$1~/DocumentRoot/{print name,$2;exit}' \
        /usr/local/apache/conf/httpd.conf | (

        read name document_root

        [[ -z "$name" ]] && echo "Cannot find '$domain'" && break

        find_suspicious_posts "$name" "$document_root"

    )
}

search_all_domains() {
    awk '$1~/ServerName/{printf $2" "}$1~/DocumentRoot/{print $2}' /usr/local/apache/conf/httpd.conf | (
        while read name document_root; do
            find_suspicious_posts "$name" "$document_root"
        done
    )
}

if [[ -z "$1" ]] ; then
    search_all_domains
    exit
fi

while [[ -n "$1" ]] ; do
    if [[ "$1" =~ ^(--help|-h)$ ]] ; then
        echo "Usage: $0 [ --help | DOMAIN [...] ]"
        echo ""
        echo "Look for files which have had successful POSTs without a referrer."
        echo "Excludes some common files, such as crons, xmlrpc, WordPress logins, etc."
        echo ""
        echo -e "\tDOMAIN\t\t\tDomain to check for POSTs. If none are given, check all domains."
        echo -e "\t-h, --help\t\tDisplay this message."
        echo ""
        exit
    fi

    search_one_domain $1
    shift
done
