#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;
use File::Slurp;
use DateTime;

=head1 NAME

    la-build_orig_schema - Tools to generate initial SQL schema

=head1 SYNOPSIS

    la-build_orig_schema

=head1 DESCRIPTION


=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'help'              => sub { pod2usage(0) },
) or pod2usage();

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item -b|--base basename

Query this specific base instead of the default one.

=back

=cut

my $LA = LATMOS::Accounts->new($config, noacl => 1);
my $labase = $LA->base($base);
$labase && $labase->load or die l("Cannot load base %s\n", $base);

my $LAVersion = LATMOS::Accounts->VERSION;
my $version = $labase->get_global_value('schema_version');
my $date = DateTime->now->iso8601;

my $text = <<EOF;
--- DataBase Schema for LATMOS-Accounts $LAVersion
--- Schema version $version build on $date

--- To properly deploy as Postgresql Admin run:
--- CREATE ROLE  laccounts LOGIN PASSWORD 'laccounts' ;
--- CREATE DATABASE laccounts OWNER laccounts encoding 'UTF-8' ;

EOF

my $command = sprintf(
    "pg_dump -x -O -s -h %s -p %d -U %s %s",
    $labase->{_db}->{pg_host},
    $labase->{_db}->{pg_port},
    $labase->{_db}->{pg_user},
    $labase->{_db}->{pg_db},
);

warn $command;

open(my $handle, "$command |") or die "Cannot run pg_dump";
while (<$handle>) {
    $text .= $_;
}
close($handle);

$text .= "\n";

$text .= "INSERT INTO settings (varname, val) VALUES ('schema_version', '$version');\n";

print $text;
