/**
 * Module:		InstURL.ycp
 *
 * Authors:		Klaus Kaempf (kkaempf@suse.de)
 *
 * Purpose:		Convert /etc/install.inf data to URL
 *
 *
 * $Id: InstURL.ycp 21878 2005-02-23 15:40:26Z jsrain $
 */

{
    textdomain "packager";

    module "InstURL";
    import "Linuxrc";
    import "URL";


    global boolean is_network = true;

    
    /**
     * Hide Password
     * @param url original URL
     * @return string new URL with hidden password
     */
    global string  HidePassword(string url) {
        map t = URL::Parse(url);
        if (size(t["pass"]:"") > 0 )
        {
            t["pass"] = "PASSWORD";
        }
        return URL::Build(t);
    }

    /**
     * Get device options for CD/DVD
     * @return string device options (devices=/dev/cdrom)
     */
    string GetDevicesOption() {
        string options = "";
        list<map> devicelist = (list<map>) SCR::Read(.probe.cdrom);
        foreach (map device, devicelist,
                {
                string devname = device["dev_name"]:"";
                if (devname != "")
                {
                if (options != "") options = options + ",";
                options = options + devname;
                }
                });
        if (options != "")
        {
            options = "devices=" + options;
        }
        return options;
    }

    /**
     *
     */
    map GetURLOptions (string url) {
        map<string,string> option_map = $[];
        integer pos = findfirstof(url, ";");
        if (pos!=nil)
        {
            string opts = substring(url, pos, size(url));
            list<string> optpairs = splitstring(opts, ";");
            option_map = listmap(string op, optpairs, ``{
                    list<string> tmp = splitstring(op, "=");
                    return($[tmp[0]:"": tmp[1]:""]);
                    });
        }
        return option_map;
    }

    /**
     *
     */
    global string  RewriteCDUrl(string url) {
        map tokens = URL::Parse(url);
        string new_url = "";
        if (tokens["scheme"]:"" == "cd" || tokens["scheme"]:"" == "dvd")
        {
            y2milestone("Old options: %1", GetURLOptions(url));
            integer pos = findfirstof(url, ";");
            if (pos != nil)
            {
                string new_options = GetDevicesOption();
                new_url = substring(url, 0, pos);
                if (size(new_options) > 0 )
                    new_url = new_url + ";" + GetDevicesOption();
                else
                    new_url = url;
            }
        } else {
            new_url = url;
        }
        return new_url;
    }
    
    /**
     * Convert install.inf to a URL useable by the package manager
     * @param extra_dir append path to original URL
     * @return string new Source URL
     */
    global string installInf2Url (string extra_dir) {
	string options = "";
        map url_tokens =  $[];

	string instmode = Linuxrc::InstallInf("InstMode");	// mode
	if (instmode == nil)	// defaults to "CD"
	{
	    instmode = "cd";
	}

	if ((instmode == "cd")					// CD or DVD
	    || (instmode == "dvd"))
	{
	    is_network = false;
            options = GetDevicesOption();
	}
	else if (instmode == "hd")						// Harddisk
	{
	    is_network = false;
            string partition = Linuxrc::InstallInf("Partition");
            if (partition != nil )
	        options = "device=/dev/" + partition + ";filesystem=auto";
            else
                y2error("no partition specified");
	}

        url_tokens["scheme"] = instmode;

	if (is_network)
	{
	    string username = Linuxrc::InstallInf("Username");
	    if ((username != nil) && (username != ""))
	    {
                url_tokens["user"] = username;
		string password = Linuxrc::InstallInf("Password");
		if ((password != nil) && (password != ""))
		{
                    url_tokens["pass"] = password;
		}
	    }
	    string servername = Linuxrc::InstallInf("Server");
	    string serverip = Linuxrc::InstallInf("ServerIP");

	    if ((servername != nil) && (servername != ""))
	    {
                url_tokens["host"] = servername;
	    }
	    else if ((serverip != nil) && (serverip != ""))
	    {
                url_tokens["host"] = serverip;
	    }

	} // is_network

	string serverdir = Linuxrc::InstallInf("Serverdir");
        /*
	if (((instmode == "hd") || is_network)				// if serverdir needed
	    && ((serverdir != nil) && (serverdir != "")))		// and is valid
	{
	    // for smb mounts it is usual to not have a leading slash
	    if (substring (serverdir, 0, 1) != "/")
		serverdir = "/" + serverdir;
	} 
        */
        string share = Linuxrc::InstallInf("Share");

	if (extra_dir != "")
	{
            if (serverdir != nil)
            {
                // avoid too many slashes
                if (findlastof(serverdir, "/") == size(serverdir) - 1)
                {
                    serverdir = substring(serverdir,  0  , size(serverdir) - 1 );
                }

                string slash = "";
                if (substring (extra_dir, 0, 1) != "/")
                    slash = "/";
	        serverdir = serverdir + slash + extra_dir;
                slash = "";
            }
            else
                serverdir = extra_dir;
	}

	if (serverdir != nil && serverdir != "")
        {
            string fs = "";
            if (instmode == "ftp" ) {
                // ftp://foo/%2fbar is %2fbar on foo  (relative)
                // ftp://foo/bar is bar on foo (absolute)
                // ftp://foo//bar is /bar on foo (relative)
               if (substring(serverdir,0,1) ==  "/" ) {
                    fs = "%2f" + substring(serverdir,1,size(serverdir));
               } else {
                   fs = serverdir;
               }

            } else if (instmode == "smb" && (share != nil) && (share != "")) {
                fs = share + "/" +  serverdir;
            } else {
                fs = serverdir;
            }
            url_tokens["path"] = fs;

        }
        else
        {
            // FIXME don't know why it is needed
            // Needed as a seperator between URL and options (!)
            url_tokens["path"] = "/"; 
        }

        string port = Linuxrc::InstallInf("Port");
        if ((port != nil) && (port != ""))
        {
            url_tokens["port"]  = port;
        }

        string url = URL::Build(url_tokens);

	if (is_network)
	{
	    string proxy = Linuxrc::InstallInf("Proxy");
	    if ((proxy != nil) && (proxy != ""))
	    {
		url = url + ";proxy=" + proxy;
	    }
	    string proxyport = Linuxrc::InstallInf("ProxyPort");
	    if ((proxyport != nil) && (proxyport != ""))
	    {
		url = url + ";proxyport=" + proxyport;
	    }
	    string proxyproto = Linuxrc::InstallInf("ProxyProto");
	    if ((proxyproto != nil) && (proxyproto != ""))
	    {
		url = url + ";proxyproto=" + proxyproto;
	    }
	    string proxyuser = Linuxrc::InstallInf("ProxyUser");
	    if ((proxyuser != nil) && (proxyuser != ""))
	    {
		url = url + ";proxyuser=" + proxyuser;
	    }
	    string proxypassword = Linuxrc::InstallInf("ProxyPassword");
	    if ((proxypassword != nil) && (proxypassword != ""))
	    {
		url = url + ";proxypassword=" + proxypassword;
	    }
	    string workgroup = Linuxrc::InstallInf ("WorkDomain");
	    if (workgroup != nil && workgroup != "")
	    {
		url = url + ";workgroup=" + workgroup;
	    }
	} // is_network

	if (options != "")
	{
	    url = url + ";" + options;
	    y2milestone ("options %1", options);
	}
	y2debug ("URL %1", HidePassword(url));
	return url;
    }
}
