#!/bin/sh
set -e

KBDB=/var/lib/kanboard/data/db.sqlite

# Create the Kanboard [sqlite] database
/usr/share/kanboard/cli db:migrate

TOK=$(sqlite3 "$KBDB" "SELECT value FROM settings WHERE option = 'api_token';")
printf 'Got JSONRPC API Token: "%s".\n' "$TOK"

VER_API=$(curl --silent --show-error --fail --user "jsonrpc:$TOK" --data '{"jsonrpc": "2.0", "method": "getVersion", "id": 1}' http://localhost/kanboard/jsonrpc.php | jq --raw-output '.result')
printf 'JSONRPC API returned Kanboard version "%s".\n' "$VER_API"

VER_DPKG=$(dpkg-query --showformat='${Version}' --show kanboard)
printf 'dpkg returned Kanboard version "%s".\n' "$VER_DPKG"

if [ "$VER_API" = "$VER_DPKG" ]; then
    printf 'Versions match; test PASSes.\n'
    exit 0
else
    printf 'Versions do NOT match; test FAILs!\n'
    exit 1
fi
