/*
 * kiosktool-tdedirs.cpp
 *
 *   Copyright (C) 2004 Waldo Bastian <bastian@kde.org>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License versin 2 as
 *   published by the Free Software Foundation.
 *
 *   This program 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include <config.h>

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>

#include <tqfile.h>

#include <tdeaboutdata.h>
#include <tdecmdlineargs.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <tdeinstance.h>
#include <kshell.h>
#include <tdesimpleconfig.h>
#include <tdestandarddirs.h>

static const char *description = I18N_NOOP("A tool to set $TDEDIRS according to the current user profile.");


static TQString readEnvPath(const char *env)
{
   TQCString c_path = getenv(env);
   if (c_path.isEmpty())
      return TQString();
   return TQFile::decodeName(c_path);
}

static TQStringList lookupProfiles(const TQString &mapFile)
{
    TQStringList profiles;

    if (mapFile.isEmpty() || !TQFile::exists(mapFile))
    {
       profiles << "default";
       return profiles;
    }

    struct passwd *pw = getpwuid(geteuid());
    if (!pw)
    {
        profiles << "default";
        return profiles; // Not good
    }

    TQCString user = pw->pw_name;
    
    gid_t sup_gids[512];
    int sup_gids_nr = getgroups(512, sup_gids);

    TDESimpleConfig mapCfg(mapFile, true);
    mapCfg.setGroup("Users");
    if (mapCfg.hasKey(user.data()))
    {
        profiles = mapCfg.readListEntry(user.data());
        return profiles; 
    }
        
    mapCfg.setGroup("General");
    TQStringList groups = mapCfg.readListEntry("groups");

    mapCfg.setGroup("Groups");

    for( TQStringList::ConstIterator it = groups.begin();
         it != groups.end(); ++it )
    {
        TQCString grp = (*it).utf8();
        // Check if user is in this group
        struct group *grp_ent = getgrnam(grp);
        if (!grp_ent) continue;
        gid_t gid = grp_ent->gr_gid;
        if (pw->pw_gid == gid)
        {
            // User is in this group --> add profiles
            profiles += mapCfg.readListEntry(*it);
        }
        else
        {
            for(int i = 0; i < sup_gids_nr; i++)
            {
                if (sup_gids[i] == gid)
                {
                    // User is in this group --> add profiles
                    profiles += mapCfg.readListEntry(*it);
                    break;
                }
            }
        }
    }

    if (profiles.isEmpty())
        profiles << "default";
    return profiles;
}

static TDECmdLineOptions options[] = {
   { "check", I18N_NOOP("Output currently active prefixes"), 0 },
   TDECmdLineLastOption
};

int main(int argc, char **argv)
{
    TDELocale::setMainCatalogue("kiosktool");
    TDEAboutData about("kiosktool-tdedirs", "kiosktool-tdedirs", "1.0", description, TDEAboutData::License_GPL, "(C) 2004 Waldo Bastian");
    TDECmdLineArgs::init( argc, argv, &about);
    TDECmdLineArgs::addCmdLineOptions(options);
    TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();

    TDEInstance a("kiosktool-tdedirs");

    if (args->isSet("check"))
    {
       (void) TDEGlobal::config(); // Force config file processing
       TQString dirs = TDEGlobal::dirs()->kfsstnd_prefixes();
       printf("%s\n", TQFile::encodeName(dirs).data());
       return 0;
    }

    TQStringList tdedirList;

    // begin TDEDIRS
    TQString tdedirs = readEnvPath("TDEDIRS");
    if (!tdedirs.isEmpty())
    {
	tdedirList = TQStringList::split(":", tdedirs);
    }
    else
    {
	TQString tdedir = readEnvPath("TDEDIR");
	if (!tdedir.isEmpty())
        {
           tdedir = KShell::tildeExpand(tdedir);
	   tdedirList.append(tdedir);
        }
    }

    TDEConfig *config = TDEGlobal::config();
    config->setGroup("Directories");
    TQString userMapFile = config->readEntry("userProfileMapFile");
    TQString profileDirsPrefix = config->readEntry("profileDirsPrefix");
    if (!profileDirsPrefix.isEmpty() && !profileDirsPrefix.endsWith("/"))
        profileDirsPrefix.append('/');
    TQStringList profiles = lookupProfiles(userMapFile);

    while(!profiles.isEmpty())
    {
        TQString profile = profiles.back();
        config->setGroup(TQString::fromLatin1("Directories-%1").arg(profile));
        profiles.pop_back();
        TQStringList list = config->readListEntry("prefixes");
        for (TQStringList::ConstIterator it = list.begin(); it != list.end(); it++)
        {
            tdedirList.prepend(*it);
	}
        if (list.isEmpty() && !profile.isEmpty() && !profileDirsPrefix.isEmpty())
        {
	   tdedirList.prepend(profileDirsPrefix + profile);
        }
    }
    printf("%s\n", TQFile::encodeName(tdedirList.join(":")).data());

    return 0;
}
