package Mojolicious::Command::clear_database;
use Mojo::Base 'Mojolicious::Command';

use C;
use L;
use DBI;


has description => 'Clear database';
has usage => sub { shift->extract_usage };

# create user CLEAN_USER with login createdb createrole noinherit password 'password';


sub run {
	my( $self, @args ) =  @_;

	$args[0]  &&  $args[0] eq '--yes'   or return;

	my $DB =  C::config->{ DbAccess };
	L::warn "Database '$DB->{ NAME }' will be dropped after 10 sec.\nPress CTRL+C to stop operation\n";
	sleep 10;

	local $DB->{ DSN };
	local $DB->{ schema } =  'DBI';
	my $dbh =  do{
		# We can not drop database we are currently on. Connect to default
		local $DB->{ NAME } =  'postgres';
		local $DB->{ USER } =  $DB->{ CLEAN_USER };
		local $DB->{ PASS } =  $DB->{ CLEAN_PASS };
		D::connect();
	};

	$dbh->do( "DROP   DATABASE IF EXISTS $DB->{ NAME }" );
	$dbh->do( "CREATE DATABASE           $DB->{ NAME }" );

	$dbh->do( <<"		SQL" =~ s!^\t\t!  !grm
		DROP ROLE IF EXISTS $DB->{ USER };
		CREATE ROLE $DB->{ USER }
		  NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN
		  PASSWORD '$DB->{ PASS }'
		;
		GRANT create ON DATABASE $DB->{ NAME } TO $DB->{ USER };
		SQL
	);


	$dbh =  do{
		# Create extension requires ROOT privilege
		local $DB->{ USER } =  'postgres';
		local $DB->{ PASS } =  $DB->{ ROOT };
		D::connect();
	};

	$dbh->do( "CREATE EXTENSION IF NOT EXISTS btree_gist" );
}

1;


=encoding utf8

=head1 NAME

Mojolicious::Command::clear_database - Drop and recreate configured database

=head1 SYNOPSIS

  Usage: APPLICATION clear_database [OPTIONS]

  Options:
    --yes   Clear database

=head1 DESCRIPTION

This command drops and recreates the configured database.

It is intentionally noisy and waits 10 seconds before continuing, to give you a
chance to abort with C<CTRL+C>.

Use this only in development/testing environments.

=head1 CONFIGURATION

The command uses C<C::config-E<gt>{DbAccess}> keys, including:

  NAME        database to drop/recreate
  CLEAN_USER  privileged user allowed to drop/create databases
  CLEAN_PASS  password for CLEAN_USER
  USER        application role to (re)create
  PASS        password for USER
  ROOT        postgres password used to create extensions

=head1 OPTIONS

=over 4

=item * C<--yes>

Perform the operation. Without this flag the command exits immediately.

=back

=head1 METHODS

=head2 run

Implements the command.

=head1 SEE ALSO

L<Mojolicious::Plugin::DbAccess>, L<D>

=cut
