/***********************************************************************
 * 
 *  Copyright (C) 2006 Novell, Inc. All Rights Reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; version 2.1
 *  of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, Novell, Inc.
 * 
 *  To contact Novell about this file by physical or electronic mail, 
 *  you may find current contact information at www.novell.com.
 * 
 ***********************************************************************/

/**
 * File:	modules/CasaAts.ycp
 * Package:	Configuration of casa-ats
 * Summary:	CasaAts settings, input and output functions
 * Authors:	Ryan Partridge <rpartridge@novell.com>
 *
 * $Id: CasaAts.ycp 27914 2006-02-13 14:32:08Z locilka $
 *
 * Representation of the configuration of casa-ats.
 * Input and output routines.
 */

{

module "CasaAts";
textdomain "casa-ats";

import "Progress";
import "Report";
import "Summary";
import "Message";
import "SuSEFirewall";
import "FileUtils";
import "Service";

/**
 * Settings Map
 */
global map Settings = $[];

string port = "2645";
string service_name = "casa_atsd";

/**
 * Prototypes
 */
global boolean Modified();

boolean ModifyFirewallPort();

/**
 * Data was modified?
 */
global boolean modified = false;

/**
 */
global boolean proposal_valid = false;

/**
 * Write only, used during autoinstallation.
 * Don't run services and SuSEconfig, it's all done at one place.
 */
global boolean write_only = false;

/**
 * Abort function
 * return boolean return true if abort
 */
global boolean() AbortFunction = Modified;

/**
 * Abort function
 * @return boolean return true if abort
 */
global define boolean Abort() ``{
    if(AbortFunction != nil)
    {
	return AbortFunction () == true;
    }
    return false;
}

/**
 * Data was modified?
 * @return true if modified
 */
global boolean Modified() {
    y2debug("modified=%1",modified);
    return modified;
}

/**
 * Read all casa-ats settings
 * @return true on success
 */
global boolean Read() {

    /* CasaAts read dialog caption */
    string caption = _("Initializing CASA ATS Configuration");

    // TODO FIXME Set the right number of stages
    integer steps = 2;

    integer sl = 500;
    sleep(sl);

    // TODO FIXME Names of real stages
    // We do not set help text here, because it was set outside
    Progress::New( caption, " ", steps, [
	    /* Progress stage 1/2 */
	    _("Read the previous settings"),
	    /* Progress stage 2/2 */
	    _("Read the firewall status")
	], [
	    /* Progress step 1/2 */
	    _("Reading the settings file..."),
	    /* Progress step 2/2 */
	    _("Reading the firewall status..."),
	    /* Progress finished */
	    _("Finished")
	],
	""
    );

    // read settings file
    if(Abort()) return false;
    Progress::NextStage();
    if (FileUtils::Exists("/etc/sysconfig/casa-ats"))
    {
        Settings["CONFIG_CASAATS_ENABLE"] = tolower((string)SCR::Read(.sysconfig.casa-ats.CONFIG_CASAATS_ENABLE)) == "yes";
        Settings["CONFIG_CASAATS_REALM"] = (string)SCR::Read(.sysconfig.casa-ats.CONFIG_CASAATS_REALM);
        Settings["CONFIG_CASAATS_HOST"] = (string)SCR::Read(.sysconfig.casa-ats.CONFIG_CASAATS_HOST);
        Settings["CONFIG_CASAATS_PROXY_USERNAME"] = (string)SCR::Read(.sysconfig.casa-ats.CONFIG_CASAATS_PROXY_USERNAME);
        string open_port = tolower((string)SCR::Read(.sysconfig.casa-ats.CONFIG_CASAATS_OPEN_PORT));
        if (open_port != nil && open_port != "")
        {
            Settings["CONFIG_CASAATS_OPEN_PORT"] = open_port == "yes";
        }
        else
        {
            Settings["CONFIG_CASAATS_OPEN_PORT"] = true;
        }
    }
    /* Error message */
    if(false) Report::Error(_("Cannot read settings file."));
    sleep(sl);

    // read firewall settings
    if(Abort()) return false;
    Progress::NextStage();
    Progress::set(false);
    SuSEFirewall::Read();
    Progress::set(true);
    /* Error message */
    if(false) Report::Error(_("Cannot read firewall status."));
    sleep(sl);

    if(Abort()) return false;
    /* Progress finished */
    Progress::NextStage();
    Progress::Finish();
    sleep(sl);

    if(Abort()) return false;
    modified = false;
    return true;
}

/**
 * Write all casa-ats settings
 * @return true on success
 */
global boolean Write() {

    /* CasaAts read dialog caption */
    string caption = _("Saving CASA ATS Configuration");

    // TODO FIXME And set the right number of stages
    integer steps = 4;

    integer sl = 500;
    sleep(sl);

    // TODO FIXME Names of real stages
    // We do not set help text here, because it was set outside
    Progress::New(caption, " ", steps, [
	    /* Progress stage 1/4 */
	    _("Write the settings"),
	    /* Progress stage 2/4 */
	    _("Execute configuration script"),
	    /* Progress stage 3/4 */
	    _("Update runlevel settings"),
	    /* Progress stage 4/4 */
	    _("Adjust firewall")
	], [
	    /* Progress step 1/4 */
	    _("Writing the settings..."),
	    /* Progress step 2/4 */
	    _("Executing configuration script..."),
	    /* Progress step 3/4 */
	    _("Updating runlevel settings..."),
	    /* Progress step 4/4 */
	    _("Adjusting firewall..."),
	    /* Progress finished */
	    _("Finished")
	],
	""
    );

    // write the settings in /etc/sysconfig/casa-ats
    if(Abort()) return false;
    Progress::NextStage();
    SCR::Write(.sysconfig.casa-ats.CONFIG_CASAATS_ENABLE, Settings["CONFIG_CASAATS_ENABLE"]:false ? "yes" : "no");
    SCR::Write(.sysconfig.casa-ats.CONFIG_CASAATS_REALM, Settings["CONFIG_CASAATS_REALM"]:"");
    SCR::Write(.sysconfig.casa-ats.CONFIG_CASAATS_HOST, Settings["CONFIG_CASAATS_HOST"]:"");
    SCR::Write(.sysconfig.casa-ats.CONFIG_CASAATS_PROXY_USERNAME, Settings["CONFIG_CASAATS_PROXY_USERNAME"]:"");
    SCR::Write(.sysconfig.casa-ats.CONFIG_CASAATS_OPEN_PORT, Settings["CONFIG_CASAATS_OPEN_PORT"]:true ? "yes" : "no");
    /* Error message */
    if(false) Report::Error (_("Cannot write settings."));
    sleep(sl);

    // run the configure script
    if(Abort()) return false;
    Progress::NextStage();
    string cmd = "/usr/share/java/CASA/authtoken/bin/CasaBasicATSSetup.sh";
    cmd = "PROXY_USER_PW=\"%1\" " + cmd;
    cmd = "PROXY_USER_NAME=\"" + Settings["CONFIG_CASAATS_PROXY_USERNAME"]:"" + "\" " + cmd;
    cmd = "LDAP_HOST_NAME=\"" + Settings["CONFIG_CASAATS_HOST"]:"" + "\" " + cmd;
    cmd = "REALM=\"" + Settings["CONFIG_CASAATS_REALM"]:"" + "\" " + cmd;
    y2milestone("Running CASA-ATS configuration script:");
    y2milestone(cmd, "******");
    map retval = (map)SCR::Execute(.target.bash_output, sformat(cmd, Settings["CONFIG_CASAATS_PROXY_PASSWORD"]:""));
    y2milestone("Return code: %1", retval["exit"]:0);
    /* Error message */
    if(false) Report::Error (_("Error executing script."));
    sleep(sl);

    // enable/disable and start/stop service as needed
    if(Abort()) return false;
    Progress::NextStage();
    if (Settings["CONFIG_CASAATS_ENABLE"]:false)
    {
        if (!Service::Enabled(service_name))
        {
            Service::Enable(service_name);
        }
        if (Service::Status(service_name) != 0)
        {
            Service::Start(service_name);
        }
        else
        {
            Service::Restart(service_name);
        }
    }
    else
    {
        if (Service::Enabled(service_name))
        {
            Service::Disable(service_name);
        }
        if (Service::Status(service_name) == 0)
        {
            Service::Stop(service_name);
        }
    }
    /* Error message */
    if(false) Report::Error (_("Error updating runlevels."));
    sleep(sl);

    // adjust firewall as needed
    if(Abort()) return false;
    Progress::NextStage();
    if (ModifyFirewallPort())
    {
        // write settings
        Progress::set(false);
        SuSEFirewall::WriteOnly();
        if (!write_only)
        {
            SuSEFirewall::ActivateConfiguration();
        }
        Progress::set(true);
    }
    /* Error message */
    if(false) Report::Error (_("Error adjusting firewall."));
    sleep(sl);

    if(Abort()) return false;
    /* Progress finished */
    Progress::NextStage();
    Progress::Finish();
    sleep(sl);

    if(Abort()) return false;
    return true;
}

/**
 * Get all casa-ats settings from the first parameter
 * (For use by autoinstallation.)
 * @param settings The YCP structure to be imported.
 * @return boolean True on success
 */
global boolean Import (map settings) {
    // TODO FIXME: your code here (fill the above mentioned variables)...
    return true;
}

/**
 * Dump the casa-ats settings to a single map
 * (For use by autoinstallation.)
 * @return map Dumped settings (later acceptable by Import ())
 */
global map Export () {
    // TODO FIXME: your code here (return the above mentioned variables)...
    return $[];
}

/**
 * Create a textual summary and a list of unconfigured cards
 * @return summary of the current configuration
 */
global list Summary() {
    // TODO FIXME: your code here...
    /* Configuration summary text for autoyast */
    return [ _("Configuration summary..."), [] ];
}

/**
 * Create an overview table with all configured cards
 * @return table items
 */
global list Overview() {
    // TODO FIXME: your code here...
    return [];
}

/**
 * Return packages needed to be installed and removed during
 * Autoinstallation to insure module has all needed software
 * installed.
 * @return map with 2 lists.
 */
global map AutoPackages() {
    // TODO FIXME: your code here...
    return $[ "install":[], "remove":[] ];
}

global boolean IsPortOpen()
{
    return contains(SuSEFirewall::GetAdditionalServices("TCP", "EXT"), port);
}

boolean ModifyFirewallPort()
{
    boolean retVal = false;
    list<string> services = SuSEFirewall::GetAdditionalServices("TCP", "EXT");
    if (!contains(services, port) && Settings["CONFIG_CASAATS_OPEN_PORT"]:false)
    {
        services = add(services, port);
        retVal = true;
    }
    else if (contains(services, port) && !Settings["CONFIG_CASAATS_OPEN_PORT"]:false)
    {
        services = filter(string service, services,
            {
                return (service != port);
            }
        );
        retVal = true;
    }
    if (retVal)
    {
        SuSEFirewall::SetAdditionalServices("TCP", "EXT", services);
    }
    return retVal;
}

/* EOF */
}