#!/usr/bin/perl

#
# 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.
#

use JSON;
use NethServer::Password;
use esmith::ConfigDB;
my $config = "/opt/mattermost/config/config.json";
my $password = NethServer::Password::store('mattermost');
my $salt = NethServer::Password->new('', {length => 32})->generate()->getAscii();

my $db = esmith::ConfigDB->open_ro() || die ("Can't open configuration db");
my $company = $db->get_prop("OrganizationContact", "Company");
my $domain = $db->get_value("DomainName");
my $host = $db->get_prop("mattermost", "VirtualHost") || '';
my $firstRun = 0;
our $data;

sub set_if_empty {
  my $section = shift;
  my $key = shift;
  my $value = shift;

  my $cur = $data->{$section}->{$key} || '';
  if ($cur eq '') {
     $data->{$section}->{$key} = $value;
  }
}


# Make sure the daemon is stopped to avoid concurrent modifications on the config file
system("/usr/bin/systemctl stop mattermost");

# Create a new config file if current one is invalid
if (system("/opt/mattermost/bin/mattermost config validate &>/dev/null") != 0) {
    system("/opt/mattermost/bin/mattermost config show --json > $config");
    # this should not be needed if the file already exists
    system("/usr/bin/chown mattermost mattermost $config");
}

my $json;
{
  local $/;
  open my $fh, "<", $config;
  $json = <$fh>;
  close $fh;
}
$data = decode_json($json);

if ($data->{'SqlSettings'}->{'DriverName'} ne "postgres") {
  $firstRun = 1;
}

# Set database connection string
$data->{'SqlSettings'}->{'DriverName'} = "postgres";
$data->{'SqlSettings'}->{'DataSource'} = "postgres://mattuser:$password\@localhost:55434/mattermost?sslmode=disable&connect_timeout=10";

# Set data directory
$data->{'FileSettings'}->{'Directory'} = "/var/lib/nethserver/mattermost/data";

# Enable mail and push notifications on the first configuration
if ($firstRun) {
  $data->{'EmailSettings'}->{'SendPushNotifications'} = JSON::true;
  $data->{'EmailSettings'}->{'PushNotificationContents'} = "full";
  $data->{'EmailSettings'}->{'PushNotificationServer'} = "https://push.mattermost.com";
  $data->{'EmailSettings'}->{'SendEmailNotifications'} = JSON::true;
  $data->{'EmailSettings'}->{'SMTPServer'} = "localhost";
  $data->{'EmailSettings'}->{'SMTPPort'} = "25";
} else {
  # Fix issue NethServer/dev#6273
  if ($data->{'EmailSettings'}->{'SMTPServer'} eq "localhost" && $data->{'EmailSettings'}->{'SMTPPort'} eq "10025") {
    $data->{'EmailSettings'}->{'SMTPServer'} = "localhost";
    $data->{'EmailSettings'}->{'SMTPPort'} = "25";
  }
}

# Configure mail notifications
set_if_empty('EmailSettings', 'InviteSalt', $salt);
set_if_empty('EmailSettings', 'FeedbackEmail', "no-reply@".$domain);
set_if_empty('EmailSettings', 'FeedbackName', "Mattermost $company");
set_if_empty('EmailSettings', 'FeedbackOrganization', $company);

# Configure logging
$data->{'LogSettings'}->{'EnableConsole'} = JSON::false;
set_if_empty('LogSettings', 'EnableFile', JSON::true);
set_if_empty('LogSettings', 'FileLevel', 'error');

# General options
if ($host ne '') {
  set_if_empty('ServiceSettings', 'SiteURL', "https://$host");
}

# Force listen adress
if ($firstRun) {
    $data->{'ServiceSettings'}->{'ListenAddress'} = '127.0.0.1:8065';
}

open my $fh, ">", $config;
print $fh encode_json($data);
close $fh;

my $uid = getpwnam 'mattermost';
my $gid = getgrnam 'mattermost';

chown $uid, $gid, $config;
