#!/bin/sh

aidebin=/sbin/aide
remotedir=/var/tmp

usage() {
  echo "Usage: $0 [user@]host init|scan|report|commit"
  echo "init:     scan host, save db as permanent"
  echo "scan:     scan host, save daily db, output the report"
  echo "report:   recompare, but don't scan"
  echo "commit:   make daily db permanent"
  exit 1
}

function confess() {
  echo "$@" 1>&2
  exit 1
}

function valid_name() {
  echo "$1" | grep -E -q '^[a-zA-Z0-9_.-]+$'
  return $?
}

function push() {
  test -f ${aidebin} || confess "aide binary (${aidebin}) missing"
  unpush
  scp -q "$@" ${aidebin} ${user}@${host}:${remotedir} || confess "cannot push aide to ${host}"
}

function unpush() {
  ssh "$@" ${user}@${host} rm -rf ${remotedir}/aide || confess "cannot erase aide from ${host}"
}

function init() {
  test -f ${config} || confess "missing config [${config}]. init failed."
  push
  cat ${config} \
    | ssh ${user}@${host} sudo ${remotedir}/aide --config - --init "$@" \
    > ${permanent_db}
  unpush
}

function scan() {
  test -f ${permanent_db} || confess "scan failed. init first."
  push
  cat ${config} ${permanent_db} \
    | ssh ${user}@${host} sudo ${remotedir}/aide --config - --update "$@" \
    > ${daily_db} 2> ${daily_report} || confess "scan failed."
  unpush
  cat ${daily_db} | gzip > ${daily_db}.gz
  cat ${daily_report}
  cat ${daily_report} | gzip > ${daily_report}.gz
  rm -f ${daily_db} ${daily_report}
}

function report() {
  test -f ${permanent_db} || confess "nothing to report. init first."
  test -f ${daily_db}.gz || confess "nothing to report. scan first."
  local tmpfile=`mktemp`
  chmod 600 ${tmpfile}
  cat ${daily_db}.gz | gunzip > ${tmpfile}
  cat ${config} ${permanent_db} \
    | ${aidebin} --config - --before="database_new=file:${tmpfile}" --compare "$@" 2>&1
  rm -f ${tmpfile}
}

function commit() {
test -f ${daily_db}.gz || confess "nothing to commit today. scan first."
  test -f ${permanent_db} && cp --preserve ${permanent_db} ${permanent_db}.bak
  cat ${daily_db}.gz | gunzip > ${permanent_db}
}

date=`date +%F`

user_host=$1
action=$2
shift 2

[ -z "$user_host" ] && usage
[ -z "$action" ] && usage

if echo $user_host | grep -q '@'; then
  user=`echo $user_host | cut -d '@' -f 1`
  host=`echo $user_host | cut -d '@' -f 2`
else
  user=`whoami`
  host=$user_host
fi

valid_name "$user" || confess "user name [$user] not valid."
valid_name "$host" || confess "host name [$host] not valid."

config=aide_${host}.conf
permanent_db=aide_${host}.db
daily_db=${host}_${date}.db
daily_report=${host}_${date}.report

case $action in
init)
	init "$@"
	;;
scan)
	scan "$@"
	;;
commit)
    commit "$@"
    ;;
report)
    report "$@"
    ;;
*)
    usage
    ;;
esac

