#!/usr/bin/env perl

# This is the script formerly known as loadDB2, and then known as NPL-update.

# It is used to update
# the database when it comes to the WeBWorK Open Problem Library (OPL).
# This should be run after doing a git clone or pull for the OPL
# files.

# In order for this script to work:
#   1) The OPL downloaded to your machine (the .pg files)
#   2) Configuration for the OPL in site.conf needs to be
#      done (basically just setting the path to the OPL files).

use strict;
use warnings;

BEGIN {
	use Mojo::File qw(curfile);
	use Env qw(WEBWORK_ROOT);

	$WEBWORK_ROOT = curfile->dirname->dirname;
}

# Get database connection
use lib "$ENV{WEBWORK_ROOT}/lib";
use lib "$ENV{WEBWORK_ROOT}/bin";
use WeBWorK::CourseEnvironment;
use Helper 'runScript';

my $ce = WeBWorK::CourseEnvironment->new({ webwork_dir => $ENV{WEBWORK_ROOT} });

print "\nDownloading the latest OPL release.\n";
runScript("$ENV{WEBWORK_ROOT}/bin/download-OPL-metadata-release.pl");

if ($ce->{problemLibrary}{showLibraryLocalStats} ||
    $ce->{problemLibrary}{showLibraryGlobalStats}) {
  print "\nUpdating Library Statistics.\n";
  runScript("$ENV{WEBWORK_ROOT}/bin/update-OPL-statistics.pl");

  print "\nLoading global statistics (if possible).\n";
  runScript("$ENV{WEBWORK_ROOT}/bin/load-OPL-global-statistics.pl");

  if ( $ENV{SKIP_UPLOAD_OPL_STATISTICS} ) {
    print "\nSkipping upload-OPL-statistics as requested\n";
  } else {
    print "\nSharing aggregated statistics\n";
    runScript("$ENV{WEBWORK_ROOT}/bin/upload-OPL-statistics.pl");
  }
}

print "\nDone.\n";

1;
