#!/usr/bin/bash

# File: aidecheck
#
# Description: This script checks a signed AIDE DB.
#
# Package: AniNIX/Sharingan
# Copyright: WTFPL
#
# Author: DarkFeather <ircs://aninix.net:6697/DarkFeather>

function usage() {
    echo "Usage: $0 [ config reference ]"
    exit $1
}

function main() {
    ### Initialize the DB
    base="$1"
    dbdir="$(grep -m 1 -E '^@@define DBDIR' "$base" | cut -f 3 -d ' ')"
    dbin="$(grep -m 1 -E '^database_in' "$base" | cut -f 2 -d '=' | sed "s#file:...DBDIR.#${dbdir}#")"
    dbout="$(grep -m 1 -E '^database_out' "$base" | cut -f 2 -d '=' | sed "s#file:...DBDIR.#${dbdir}#")"

    set -x

    if ! gpg --verify "$dbin".sig "$dbin"; then
        echo "$dbin doesn't match signature."
        exit 1
    fi

    sudo aide -c "$base" -C

}

### MAIN
if [ `basename "$0"` == "aidecheck" ]; then

    # Allow -h for helptext
    if [ "$1" == '-h' ]; then
        echo "Checks an AIDE DB"
        usage 0
    else

        # Find the config
        if [ -z "${1}" ]; then
            base='/etc/aide.conf'
        else
            base="/etc/aide/${1}.conf"
        fi
        if [ -f "$base" ]; then
            main "$base"
        else

            # If it doesn't, explain and exit.
            echo "$base does not exist"
            usage 1
        fi
    fi
fi
