#!/usr/bin/perl

#
# Copyright (C) 2019 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.
#

use strict;
use NethServer::ApiTools;
use JSON;

my $output = {};
my $input = NethServer::ApiTools::readInput();

my $action = $input->{'action'};

# get nextcloud props
my $db = esmith::ConfigDB->open_ro();
my $nextcloud = $db->get('nextcloud');
my %props;
if ($nextcloud) {
    %props = $nextcloud->props;
    foreach (qw(TrustedDomains VirtualHost Wellknown)) {
        $output->{'props'}{$_} = $props{$_};
    }
}

if ($action eq 'app-info') {
    my $protocol = $input->{'location'}->{'protocol'};
    my $host = $input->{'location'}->{'hostname'};
    $output = {
        'url' => $props{"VirtualHost"} eq "" ? "$protocol//$host/nextcloud" : "$protocol//".$props{"VirtualHost"},
    };
} elsif ($action eq 'configuration') {

    # get stats
    my $version = `/usr/local/sbin/occ status 2>/dev/null | grep versionstring: | awk '{print \$3}'`;
    chomp($version);
    my $users = `/usr/local/sbin/occ user:list 2>/dev/null | wc -l`;
    chomp($users);

    # read pass and check if is changed
    my $hashPass = `mysql -S /run/rh-mariadb105-mariadb/nextcloud-mysql.sock nextcloud -B -N -e "select password from oc_users where uid='admin'" | cut -d'|' -f 2`;
    chomp($hashPass);
    my $adminPassWarn = `source /opt/remi/php80/enable; php /usr/libexec/nethserver/api/nethserver-nextcloud/admin-password-helper '$hashPass'`;

    # build the output
    $output->{'stats'} = {
        "version" => $version,
        "users" => $users,
        "admin_pass_warn" => ($? > 0) ? JSON::true : JSON::false,
    }
} else {
    NethServer::ApiTools::error();
}

print encode_json($output);
