#!/usr/bin/bash

# File: aideinit
#
# Description: This script initializes an AIDE DB and signs it
#
# 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}#")"

    # sudo chattr -i "$dbin"*

    sudo aide -c "$base" -i 2>&1 | sudo tee "$dbin".out
    sudo mv "$dbout" "$dbin"
    sudo chmod 0644 "$dbin"
    gpg -bs --output - "$dbin" | sudo tee "$dbin".sig &>/dev/null
    sudo chown root: "$dbin"*
    sudo chmod 0755 "$dbin"*
    # sudo chattr +i "$dbin"*
}

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

    # Allow -h for helptext
    if [ "$1" == '-h' ]; then
        echo "Initializes 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
