#!/bin/bash

#
# Copyright (C) 2018 Nethesis S.r.l.
# http://www.nethesis.it - nethserver@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see COPYING.
#

function _query
{
    echo $1 | su - postgres  -c "scl enable rh-postgresql12 -- psql  --port=55434 -t -d mattermost 2>/dev/null| tr -d '[:space:]' 2>/dev/null"
}

input=$(cat)
action=$(jq -r .action <<<"$input")

if [[ $action == "app-info" ]]; then
    if [[ $(/sbin/e-smith/config getprop mattermost status) == "enabled" ]]; then
        vhost=$(/sbin/e-smith/config getprop mattermost VirtualHost)
        printf '{"url":"%s"}' "https://${vhost}"
    else
        printf '{}'
    fi
else
    users=$(_query "select count(*) from users where deleteat = 0")
    teams=$(_query "select count(*) from teams where deleteat = 0")
    channels=$(_query "select count(*) from channels where deleteat = 0")
    posts=$(_query "select count(*) from posts where deleteat = 0")

    database_usage=$(su - postgres -c "scl enable rh-postgresql12 -- psql -q -A -t --port=55434 -c 'SELECT  pg_database_size('\''mattermost'\'');'")
    data_usage=$(/usr/bin/du -sb /var/lib/nethserver/mattermost | cut -f1)

    prop=$(/sbin/e-smith/config getjson mattermost)
    printf '{"status": { "users": "%s", "teams": "%s", "channels": "%s", "posts": "%s", "database-usage": "%s", "data-usage": "%s" },"configuration":%s}' "$users" "$teams" "$channels" "$posts" "$database_usage" "$data_usage" "$prop"
fi

