#!/bin/sh

if [ -z "${AUTOPKGTEST_TMP:-}" ]; then
  export PATH="${0%/*}/../../src:$PATH"
fi

config=${0%/*}/goaccess.conf
logfile=${0%/*}/log

oneTimeSetUp() {
  tmpdir=$(mktemp --tmpdir --directory goaccess.autopkgtest.XXXXXXXXXX)
  stats_output="$tmpdir/output"
  stats_db="$tmpdir/db"
  mkdir -p "$stats_output" "$stats_db"

  htmlrc=0
  goaccess \
    --config-file="$config" \
    --db-path="$stats_db" \
    --restore \
    --persist \
    --html-prefs='{"theme":"bright","perPage":20,"layout":"vertical","showTables":true}' \
    --html-report-title="access statistics" \
    --output "$stats_output/index.html" \
    "$logfile" || htmlrc=$?

  jsonrc=0
  goaccess \
    --config-file="$config" \
    --db-path="$stats_db" \
    --restore \
    --persist \
    --output "$stats_output/data.json" \
    "$logfile" || jsonrc=$?
}

oneTimeTearDown() {
  if [ -n "${DISPLAY:-}" ]; then
    echo "I: not removing tmpdir ${tmpdir} so that you can inspect the results in a browser"
    echo "I: please check file://${stats_output}/index.html"
  else
    rm -rf "$tmpdir"
  fi
}

test_db() {
  size="$(du -sh "$stats_db" | awk '{print($1)}')"
  assertEquals "$size" "$(printf "0M\n%s\n" $size | sort --human | tail -1)"
}

test_html_rc() {
  assertEquals "HTML output failed" 0 "$htmlrc"
}

test_html() {
  assertTrue "HTML output: index.html created" "test -f $stats_output/index.html"
}

test_json_rc() {
  assertEquals "JSON output failed" 0 "$jsonrc"
}

test_json() {
  assertTrue "JSON output: data.json created" "test -f $stats_output/data.json"
}

test_html_visual() {
  if [ -n "${DISPLAY:-}" ]; then
    x-www-browser "$stats_output/index.html"
 fi
}

. shunit2
