/*
 * kiosktool-kdedirs.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 <qfile.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <klocale.h>
#include <kinstance.h>
#include <kshell.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>

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


static QString readEnvPath(const char *env)
{
   QCString c_path = getenv(env);
   if (c_path.isEmpty())
      return QString::null;
   return QFile::decodeName(c_path);
}

static QStringList lookupProfiles(const QString &mapFile)
{
    QStringList profiles;

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

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

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

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

    mapCfg.setGroup("Groups");

    for( QStringList::ConstIterator it = groups.begin();
         it != groups.end(); ++it )
    {
        QCString 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 KCmdLineOptions options[] = {
   { "check", I18N_NOOP("Output currently active prefixes"), 0 },
   KCmdLineLastOption
};

int main(int argc, char **argv)
{
    KLocale::setMainCatalogue("kiosktool");
    KAboutData about("kiosktool-kdedirs", "kiosktool-kdedirs", "1.0", description, KAboutData::License_GPL, "(C) 2004 Waldo Bastian");
    KCmdLineArgs::init( argc, argv, &about);
    KCmdLineArgs::addCmdLineOptions(options);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KInstance a("kiosktool-kdedirs");

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

    QStringList kdedirList;

    // begin KDEDIRS
    QString kdedirs = readEnvPath("KDEDIRS");
    if (!kdedirs.isEmpty())
    {
	kdedirList = QStringList::split(":", kdedirs);
    }
    else
    {
	QString kdedir = readEnvPath("KDEDIR");
	if (!kdedir.isEmpty())
        {
           kdedir = KShell::tildeExpand(kdedir);
	   kdedirList.append(kdedir);
        }
    }

    KConfig *config = KGlobal::config();
    config->setGroup("Directories");
    QString userMapFile = config->readEntry("userProfileMapFile");
    QString profileDirsPrefix = config->readEntry("profileDirsPrefix");
    if (!profileDirsPrefix.isEmpty() && !profileDirsPrefix.endsWith("/"))
        profileDirsPrefix.append('/');
    QStringList profiles = lookupProfiles(userMapFile);

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

    return 0;
}
