/**
 * File:
 *   osr_module_packages.ycp
 *
 * Module:
 *   YaST2 Repair packages module.
 *
 * Summary:
 *   YaST2 Repair. Automatic error detection & repair tool for Linux.
 *
 * Author:
 *   Johannes Buchhold <jbuch@suse.de>
 *
 * $Id: osr_module_packages.ycp 21333 2005-02-07 15:59:08Z jsuchome $
 */

{
  textdomain "repair";

  import "Popup";
  import "Report";
  import "Stage";

  import "OSRCommon";
  import "OSRPkg";
  import "OSRPkgVerify";
  import "OSRSummary";
  import "OSRStatus";
  import "OSRSystem";
  import "OSRFstab";
  import "OSRPopup";
  import "OSR";



  //////////////////////////////////////////////////////////////////////
  //
  //  DETECTION METHODS
  //
  //////////////////////////////////////////////////////////////////////

  /**
   * Mount all partitions specified in the fstab
   */
  define boolean OSRPackagesMountAll()``{

      if( ! OSRFstab::ReadedSuccessfully())
      OSRCommon::ProvideList("just_umounted", OSRFstab::UmountAllFrom( OSRSystem::TargetRoot()));

      list<map> mounted      = OSRFstab::MountAll( OSRSystem::TargetRoot());
      list<map> success      = filter(map mpe , mounted, ``(mpe["status"]:false == true));

      if( mounted == nil )
      {
        // summary text
        OSRSummary::DetectError("",_("Target system was not initialized."));
        OSRStatus::Cancel();
        return false;
      }

      list<map> failed       = filter(map mpe,  mounted, ``(mpe["status"]:true  == false));
      if( size(failed) > 0 )
      {
        OSRSummary::DetectProblem("",
            // summary text
            sformat(_("Following devices cannot be mounted:<br>%1"),
                mergestring(maplist(map mpe, failed, ``(sformat("%1",mpe["partition"]:""))), "<br>")));


      }
      else {
        // summary text
        OSRSummary::DetectOK("", _("Target system initialized."));
      }

      OSRCommon::ProvideBoolean("mounted_all", true );
      OSRCommon::ProvideList("just_mounted", union( OSRCommon::RequireList("just_mounted"), success));

      return true;
  }

  /**
   *
   */
  define boolean OSRPackagesDBFind() ``{
    /////////////////////////////////////////////////////////////////////////
    //
    //
    //
    /////////////////////////////////////////////////////////////////////////
    if ( OSRPkg::CheckDB (OSRSystem::TargetRoot()))
    {
	// summary text
        OSRSummary::DetectOK ("",_("Package database was found."));
        OSRCommon::ProvideBoolean ("package_db_found", true);
    }
    else
    {
        // summary text
        OSRSummary::DetectError ("", _("No package database was found."));
        OSRSummary::SetRepairSummary (OSRPkg::RepairDB(),
                       // summary header
                       _("Initializing new package database..."),
                       // summary text
                       _("Successfully initialized new package database."),
                       // summary text
                       _("Skipped initializing new package database."),
                       // summary text
                       _("Initialization of the new package database was not successful."));

    }
    // now check the correct product version: (#45306)
    if (! OSRPkg::CheckProductVersions ())
    {
	// error text in summary
	OSRSummary::DetectError ("", _("Different versions of products."));
	OSRStatus::ErrorSeverityModuleBlocking ();
	// error popup, %1 is tool name
	Popup::Error (sformat (_("You are using %1 from a product 
different than the installed one.

Because the package database of the installed product 
can be broken, only the package database on the installation 
media is used for package database checking. 
 
Checking the package database is not possible and will be skipped."),
	OSRCommon::tool_name));
    }

    return true;
  }

  /**
   *
   */
  define boolean OSRPackagesCheckMinimumSelection()``{
      /////////////////////////////////////////////////////////////////////////
      //
      //
      //
      /////////////////////////////////////////////////////////////////////////
      if ( OSRPkg::CheckMinimum(""))
      {
        // summary text
        OSRSummary::DetectOK("",_("All minimal required packages were found."));
        OSRCommon::ProvideBoolean("package_minimal_selection", true);
      }
      else {
        OSRSummary::DetectError("",
            // summary text
            _("Some packages of the minimal requirement were missing."));
        OSRSummary::SetRepairSummary(OSRPkg::InstallMissing(true),
                    // summary heder
                    _("Install Missing Packages"),
                    // summary text
                    _("Installation of missing packages was successful."),
                    // summary text
                    _("Installation of missing packages was skipped."),
                    // summary text
                    _("Installation of missing packages was not successful."));
      }
      return true;
  }

  /**
   *
   */
  define boolean OSRPackagesVerifyPackages(string what)``{

    /////////////////////////////////////////////////////////////////////////
    //
    //
    //
    /////////////////////////////////////////////////////////////////////////

    symbol ret = OSRPkg::VerifyPackages("", what, false, true );

    if( ret == `abort || ret == `cancel )
    {
	// summary text
	OSRSummary::DetectOmit("", _("Package verification was canceled."));
    }
    else if (ret == `error || ret == `different_products)
    {
	// summary text
        OSRSummary::DetectError("", _("Package verification failed."));
    }
    else if ( size( OSRPkg::missing_packages ) > 0 )
    {
	OSRSummary::SetRepairSummary( OSRPkg::InstallMissing(true),
                "",
                // summary text
                _("Reinstallation of unverified packages was successful."),
                // summary text
                _("Reinstallation of unverified packages was skipped."),
                // summary text
                _("Reinstallation of unverified packages was not successful."));
    }
    else if ( size( OSRPkg::missing_packages ) == 0 )
    {
        // summary text
        OSRSummary::DetectOK("", _("All packages were verified successfully."));
    }

    //Not a second verify process!!
    OSRStatus::DetectOK();
    OSRCommon::ProvideBoolean("package_verified", true);
    return true;
  }

  /**
   * wrapper
   */
  define boolean OSRPackagesVerifyBasePackages() ``{

      return OSRPackagesVerifyPackages ("base");
  }

  /**
   * wrapper
   */
  define boolean OSRPackagesVerifyAllPackages() ``{

      return OSRPackagesVerifyPackages ("all");
  }

  define symbol OSRDirectPackageCheck()``{
      symbol ret       = `next;
      // radio button label
      string sret      = _("Base Packages Only");
      // radio button label
      list<string> options = [ sret , _("All Installed Packages") ];

      UI::NormalCursor();
      if( ! Stage::initial () )
      {
        // RadioButtonGroup label
        sret = OSRPopup::RadioButtonGroup(_("Select the package count:"),
            // RadioButtonGroup text
            _("
You have the possibility to verify all packages
or only the base packages. Verifying all packages 
is very time consuming.
"),
            options,
            options[0]:"",
            false);
      }

      if ( sret == "" )
      {
      ret = `cancel;
      }
      else
      {
	symbol verified = OSRPkg::VerifyPackages (OSRSystem::TargetRoot(),
	    ( options[0]:"" == sret ) ? "base" : "all",
	    false, true);

	if (verified == `different_products)
	{
	    Popup::Error (_("Cannot initialize package database."));
	}
	else if (OSRPkg::missing_packages != [])
	{
	    OSRPkg::InstallMissing(true);
	}
	else
	{
	    Report::Message (sformat(_("YaST verified %1 packages successfully.
"), OSRPkgVerify::VerifiedSize ()));

	}
      }

      OSRFstab::Reset();
      OSRPkg::Reset();
      y2milestone("Direct package check");
      return ret;
  }

  /**
   *  Reset boot loader temporary settings.
   */
  define boolean OSRPackagesReset() ``{

      OSRSystem::SetOrgRoot();
      OSRPkg::Reset();
      return true;
  }

  /**
   *  Initialization of the module map that contains all important information
   *  for this module.
   *
   *  @return map The map that contains all information about the module
   *  osr_module_packages
   */
  define map OSRPackagesInit() ``{

      y2milestone("OSRPackagesInit");

      // helptext
      string common_package_texts = _("The most common way to add a new program or library
to a Linux system is to install a new package.
In doing so, the install routine copies all files of the
package to the target and registers the package in
the package database.
");

      // helptext, %1 add one more sentence
      string verify_package_text = sformat(_("
%1
The package database administers all
information about the installed software packages.
Verifying a package means that the information
in the package database about a package will be
compared with the actual installed files.
"), common_package_texts );

      map global_menu_entries = $[
                  "packages_db_check" : $[
                                  // module action label
                         "text" : _("Check Package Database"),
                         "help" : sformat(_("
<P><B>What is the package database?</B><BR>
The package database administers all
information about the installed software packages.
%1
This makes it possible to remove the package later.</P>
"), common_package_texts ) +
// helptext
_("<P><B>Check Package Database</B><BR>
YaST checks all files that pertain to the
package database. If some files are missing
or the package database cannot be opened,
YaST allows rebuilding the database or
reverting to a backup.</P>
")
                      ],
                  "packages_selection" : $[
                                  // module action label
                         "text" : _("Check Minimal Package Selection"),
                                  // helptext
                         "help" : sformat(_("

<P><B>What is the minimal package selection?</B><BR>
%1
&product; needs at least some packages for
the basic system functionality. Without these
packages, the system is not executable.</P>
"), common_package_texts ) +

// helptext
_("<P><B>Check Minimal Package Selection</B><BR>
YaST checks if all packages of a minimal installation
are installed. If
some packages are missing, YaST proposes
installing the missing packages.</P>
"),
                         "requires" : [ "packages_db_check"]
                      ],
                  "packages_verify_base" :
                      $[
                                  // module action label
                        "text"  : _("Verify Base Packages (time consuming)"),
                                  // helptext
                        "help"  : sformat(_("
<P><B>What does verify packages mean?</B><BR>
%1
</P>
"), verify_package_text ) +

// helptext
_("<P><B>Verify Base Package</B><BR>
YaST verifies all package that belong
to the minimal selection. If
discrepancies appear, YaST suggests
reinstalling the damaged packages.</P>
"),
                         "requires" : [ "packages_db_check"]
                      ]
      ];

      if( ! Stage::initial () )
      {
      global_menu_entries[ "packages_verify_all" ] =
                      $[
                                  // module action label
                        "text"  : _("Verify All Installed Packages (very time consuming)"),
                                  // helptext
                        "help"  : sformat(_("
<P><B>What does verify packages mean?</B><BR>
%1
</P>
"), verify_package_text ) +

// helptext
_("<P><B>Verify All Installed Packages</B><BR>
YaST verifies all installed packages. If
discrepancies appear, YaST suggests
reinstalling the damaged packages. Verifying
all packages is very time consuming. Therefore,
this menu entry does not belong to the default
selection.</P>
"),
                        "selected"  : false,
                        "requires" : [ "packages_db_check"]
                      ];
      }

      map ret =  $[
          "name"              :  "osr_module_packages",
                                 // module headline
          "headline"          :  _("Packages"),
          "global_entries"    : global_menu_entries,
          "static_provides"   : $[],
          "reset_methods"     : [
                      $[
                                      // module reset label
                        "summary"   : _("Reset Package Check Settings"),
                        "method"    : OSRPackagesReset,
                        "provides"  : 10
                      ]
          ],
          // the sequence of the detection methods of this module
          "detect_methods"    :  [
                      $[ "name" : "mount_all",
                                      // module method progress label
                         "summary"  : _("Mounting all partitions..."),
                         "method"   : OSRPackagesMountAll,
                         "requires" :  [ "fstab_checked" ],
                         "provides" :  [ "mounted_all" ],
                         "group"    : "packages_db_check",
                         "progress" : 10
                      ],
                      $[ "name" : "find_package_db",
                                      // module method progress label
                         "summary"  : _("Searching for package database..."),
                         "method"   : OSRPackagesDBFind,
                         "requires" :  [ "mounted_all" ],
                         "provides" :  [ "package_db_found" ],
                         "group"    : "packages_db_check",
                         "progress" : 10
                      ],
                      $[ "name" : "find_minimal_selection",
                                      // module method progress label
                         "summary"  : _("Searching for minimal required packages..."),
                         "method"   : OSRPackagesCheckMinimumSelection,
                         "requires" :  [ "package_db_found" ],
                         "provides" :  [ "package_minimal_selection" ],
                         "group"    : "packages_selection",
                         "progress" : 10
                      ],
                      $[ "name" : "verify_base_packages",
                                      // module method progress label
                         "summary"  : _("Verifying base packages..."),
                         "method"   : OSRPackagesVerifyBasePackages,
                         "requires" :  [ "package_minimal_selection" ],
                         "provides" :  [ "package_base_verified" ],
                         "group"    : "packages_verify_base",
                         "progress" : 10
                      ]
          ],

          "direct_methods" : [
                      $[
                    "name"      : "direct_methods_verify_packages",
                                      // module method acton label
                    "button_text"   : _("Verify Installed Software"),
                                      // module method description
                    "description"   : _("
If you have problems with some installed
applications, select this to check
all software packages.
"),
                    "method"        : OSRDirectPackageCheck,
                    "initial_only"  : false,
                    "visible"       : true,
                    "initial_root"  : true
                    ]
          ]
      ];

      if ( ! Stage::initial () )
      {
      ret[ "detect_methods" ] = add(  ret[ "detect_methods" ]:[],
                      $[ "name"     : "verify_all_packages",
                                      // module method progress label
                         "summary"  : _("Verifying all installed packages..."),
                         "method"   : OSRPackagesVerifyAllPackages,
                         "requires" :  [ "package_minimal_selection" ],
                         "provides" :  [ "package_all_verified" ],
                         "group"    : "packages_verify_all",
                         "progress" : 10
                      ] );
      }
      return ret;

  }



  /*
  integer arg_n = 0;
  //////////////////////////////////////////////////////////////////////
  //
  //  MAIN
  //
  //////////////////////////////////////////////////////////////////////
  while ( arg_n <  size(WFM::Args()) )
  {
      if ( WFM::Args(arg_n) == .init )
      {
	y2milestone("Argument: %1", WFM::Args(arg_n));
	return OSRPackagesInit();
      }
      else
      {
	y2error("ERROR: unknown option %1", WFM::Args(arg_n) );
	return $[];
      }
      arg_n = arg_n + 1;
  }
  */
}//EOF
