/**
 * File:
 *   modules/CheckMedia.ycp
 *
 * Summary:
 *   Module for checking media intergrity
 *
 * Authors:
 *   Ladislav Slezak <lslezak@suse.cz>
 *
 * $Id: CheckMedia.ycp 21719 2005-02-18 13:58:02Z lslezak $
 *
 * Input and output routines.
 *
 */

{
    // Set the name of the module
    module "CheckMedia";
    import "Report";

    textdomain "packager";

    string checkmedia = "/usr/bin/checkmedia";

    list<string> output = [];
    integer progress = 0;
    boolean inprogress = false;

    global string preferred_drive = "";

    // true if module start was forced - check=1 was found in the application area,
    // effects UI a little
    global boolean forced_start = false;

    // cache .probe.cdrom value
    // avoid reprobind during installation
    global list<map> cd_cache = nil;

    global define boolean Start(string device) {
	// reset values
	output = [];
	progress = 0;
	inprogress = false;

	boolean ret = (boolean)SCR::Execute(.background.run_output, checkmedia + " " + device);
	return ret;
    }

    global define boolean Stop() {
	boolean ret = (boolean)SCR::Execute(.background.kill);

	return ret;
    }

    global define void Process() {
	if (inprogress)
	{
	    // try to read whole lines
	    list<string> out = (list<string>)SCR::Read(.background.newout);

	    if (out != nil && size(out) > 0)
	    {
		// remove the first part of the output
//		out = remove(out, 0);
		output = (list<string>)merge(output, out);

		// finished
		progress = 100;
		inprogress = false;
	    }
	    else
	    {
		// read progress status
		string buffer = (string)SCR::Read(.background.buffer_out);

		if (buffer != "")
		{
		    y2debug("buffer: %1", buffer);

		    string percent = regexpsub(buffer, "([0-9]*)%.*$", "\\1");

		    if (percent != nil)
		    {
			progress = tointeger(percent);
			y2milestone("progress: %1%%", progress);
		    }
		}
	    }
	}
	else
	{
	    list<string> out = (list<string>)SCR::Read(.background.newout);

	    if (out != nil && size(out) > 0)
	    {
		if (false)
		{
		    inprogress = true;
		}

		output = (list<string>)merge(output, out);

		// check whether we need to switch to progress mode
		string last = out[size(out) - 1]:"";
		if (regexpmatch(last, "^ *md5: "))
		{
		    inprogress = true;
		    y2milestone("Switching into progress mode");
		}
	    }
	}

	return;
    }

    global define boolean Running() {
	boolean ret = (boolean)SCR::Read(.background.output_open);
	return ret;
    }

    /**
     * Return information printed by checkmedia utility
     * @ret list<string> checkmedia output
     */
    global define list<string> Info() {
	list<string> ret = output;
	output = [];
	return ret;
    }

    global define integer Progress() {
	return progress;
    }

}
