// file      : bpkg/pkg-configure.hxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#ifndef BPKG_PKG_CONFIGURE_HXX
#define BPKG_PKG_CONFIGURE_HXX

#include <libbpkg/manifest.hxx>     // version
#include <libbpkg/package-name.hxx>

#include <libbuild2/context.hxx>
#include <libbuild2/variable.hxx> // variable_overrides

#include <bpkg/types.hxx>
#include <bpkg/forward.hxx> // transaction, selected_package
#include <bpkg/utility.hxx>

#include <bpkg/package.hxx>               // package_prerequisites,
                                          // dependencies.
#include <bpkg/package-skeleton.hxx>
#include <bpkg/pkg-configure-options.hxx>

namespace bpkg
{
  int
  pkg_configure (const pkg_configure_options&, cli::scanner& args);

  // Configure a system package and commit the transaction.
  //
  shared_ptr<selected_package>
  pkg_configure_system (const package_name&,
                        const version&,
                        database&,
                        transaction&);

  // The custom search function. If specified, it is called by pkg_configure()
  // to obtain the database to search for the prerequisite in, instead of
  // searching for it in the linked databases, recursively. If the function
  // returns NULL, then fallback to the recursive search through the linked
  // databases.
  //
  using find_database_function = database* (database&,
                                            const package_name&,
                                            bool buildtime);

  // Given dependencies of a package, return its prerequisite packages,
  // 1-based indexes of the selected dependency alternatives (0 for toolchain
  // build-time dependencies, etc), the constrains manifest values presence
  // flag, configuration variables that resulted from selection of these
  // prerequisites (import, reflection, etc), and sources of the configuration
  // variables resulted from evaluating the reflect clauses. Fail if for some
  // of the dependency alternative lists there is no satisfactory alternative
  // (all its dependencies are configured, satisfy the respective version
  // constraints, etc).
  //
  // The package dependency version constraints are expected to be complete.
  //
  // The dependencies argument may contain pre-selected dependency
  // alternatives (with the potential empty entries for the toolchain
  // build-time dependencies, dependencies with all the alternatives disabled,
  // and disabled or inactive dependency constraints; see pkg-build for the
  // use-case). In this case the number of dependency alternatives for each
  // dependency must be 1 (or 0) and the alternatives argument must be
  // specified. The alternatives argument must be parallel to the dependencies
  // argument and specify indexes of the selected alternatives.
  //
  // If the dependency alternatives are not pre-selected (alternatives ==
  // NULL), then for each depends value select the first satisfactory
  // alternative encountered. If, however, prerequisites corresponding to the
  // previous configured state of the package are specified
  // (prev_prerequisites != NULL), then for each depends value try to select
  // an alternative where dependencies all belong to this list (the "recreate
  // dependency decisions" mode). Failed that, select an alternative as if no
  // prerequisites are specified (the "make dependency decisions" mode). Note
  // that prev_prerequisites, if specified, should only refer to the
  // prerequisites of the dependency type.
  //
  // For the dependency constraints contained in the dependencies argument,
  // regardless of whether it is pre-selected or not, deduce if these
  // constraints are active or not. Resolve the prerequisites for the active
  // constraints and silently skip the inactive ones.
  //
  // Note that there are actually 3 possible use cases for
  // pkg_configure_prerequisites():
  //
  // - The package is being configured manually. In this case its dependency
  //   alternatives are not pre-selected and there is no information about its
  //   previous configured state (alternatives == NULL, prev_prerequisites ==
  //   NULL).
  //
  // - The package is being built, upgraded, or re-evaluated. In this case its
  //   dependency alternatives are pre-selected, their enable, prefer, and
  //   require clauses are evaluated, and there is no need in the previous
  //   configured state information (alternatives != NULL, prev_prerequisites
  //   == NULL).
  //
  // - The package is being reconfigured for a reason other than any of the
  //   mentioned above (dependency up/down-grade/reconfiguration, deorphaning,
  //   pkg-build --disfigure is specified, etc). In this case its dependency
  //   alternatives are not pre-selected but the previous configured state
  //   information is provided (alternatives == NULL, prev_prerequisites !=
  //   NULL).
  //
  // - There are no use cases when both dependency alternatives are
  //   pre-selected and the previous configured state information needs to be
  //   provided. Thus, alternatives and prev_prerequisites must never be both
  //   not NULL.
  //
  // Optionally, remove version constraints from the specified dependencies
  // (unconstrain_deps). Only allowed in the simulation mode.
  //
  struct configure_prerequisites_result
  {
    package_prerequisites prerequisites;
    vector<size_t>        dependency_alternatives;
    strings               config_variables;        // Note: name and value.

    // Only contains sources of configuration variables collected using the
    // package skeleton and doesn't contain variables that may be passed by
    // bpkg itself (config.*.build.readonly, config.config.disfigure, etc).
    // Thus, it is not parallel to the config_variables member.
    //
    // Note that besides the project variables for the specified package, it
    // may also contain the user-specified configuration variables for build2
    // modules (config.cc.*, etc).
    //
    vector<config_variable> config_sources; // Note: name and source.

    // XXH64 checksum of variables (names and values) referred to by the
    // config_sources member.
    //
    string config_checksum;

    // True if there are constrains values in the package manifest.
    //
    bool has_dependency_constraint;

    configure_prerequisites_result (): has_dependency_constraint (false) {}
    configure_prerequisites_result (package_prerequisites prs,
                                    vector<size_t> das,
                                    strings cvs,
                                    vector<config_variable> css,
                                    string cc,
                                    bool hdc)
        : prerequisites (move (prs)),
          dependency_alternatives (move (das)),
          config_variables (move (cvs)),
          config_sources (move (css)),
          config_checksum (move (cc)),
          has_dependency_constraint (hdc) {}
  };

  // Return the "would be" state for packages that would be configured
  // by this stage.
  //
  using find_package_state_function =
    optional<pair<package_state, package_substate>> (
      const shared_ptr<selected_package>&);

  struct configure_previous_prerequisite
  {
    package_name name;
    bool         buildtime;
    bool         runtime;
  };

  // Note: loads selected packages.
  //
  configure_prerequisites_result
  pkg_configure_prerequisites (
    const common_options&,
    database&,
    transaction&,
    const dependencies&,
    const vector<size_t>* alternatives,
    package_skeleton&&,
    const vector<configure_previous_prerequisite>*,
    bool simulate,
    const function<find_database_function>&,
    const function<find_package_state_function>&,
    const function<find_package_prerequisites_function>&,
    const vector<package_key>* unconstrain_deps = nullptr);

  // Configure the package, update its state, and commit the transaction.
  //
  // This is a lower-level version meant for sharing the same build context
  // to configure multiple packages (in the dependency order).
  //
  // Note: variable_overrides must include config.config.disfigure, if
  //       required.
  //
  // Note: expects all the non-external packages to be configured to be
  //       already unpacked (for subproject discovery).
  //
  // If no_progress is true, then suppress progress in the underlying build
  // system invocations (for example, because you are printing your own
  // progress). Actually, currently this has to be done before creating
  // the context (since the value of build2::diag_progress_option is set
  // as a global scope variable).
  //
  void
  pkg_configure (const common_options&,
                 database&,
                 transaction&,
                 const shared_ptr<selected_package>&,
                 configure_prerequisites_result&&,
                 const unique_ptr<build2::context>&,
                 const build2::variable_overrides&,
                 bool no_progress,
                 bool simulate);

  // Create a build context suitable for configuring packages.
  //
  unique_ptr<build2::context>
  pkg_configure_context (
    const common_options&,
    strings&& cmd_vars,
    const function<build2::context::var_override_function>&,
    bool no_progress);

  // This is a higher-level version meant for configuring a single package.
  //
  // Note: loads selected packages.
  //
  // Note: has no way to suppress build system progress (unlike above).
  //
  void
  pkg_configure (const common_options&,
                 database&,
                 transaction&,
                 const shared_ptr<selected_package>&,
                 const dependencies&,
                 const vector<size_t>* alternatives,
                 package_skeleton&&,
                 const vector<configure_previous_prerequisite>*,
                 bool disfigured,
                 bool simulate,
                 const function<find_database_function>& = {});
}

#endif // BPKG_PKG_CONFIGURE_HXX
