const fs = require('fs');

module.exports = function (app, checkApiKey) {
    app.get('/action/getgroups', checkApiKey, (req, res) => {
        const authzFilePath = '/etc/apache2/dav_svn.authz';

        try {
            const fileContent = fs.readFileSync(authzFilePath, 'utf8');
            const lines = fileContent.split('\n');

            let groups = [];
            let inGroupsSection = false;

            for (const line of lines) {
                const trimmed = line.trim();

                // Début de la section [groups]
                if (trimmed === '[groups]') {
                    inGroupsSection = true;
                    continue;
                }

                // Fin de la section [groups]
                if (inGroupsSection && trimmed.startsWith('[')) {
                    break;
                }

                // Lire les groupes
                if (inGroupsSection && trimmed.includes('=')) {
                    const groupName = trimmed.split('=')[0].trim();
                    groups.push(groupName);
                }
            }

            res.json({
                groups: groups,
                count: groups.length
            });

        } catch (error) {
            res.status(500).json({
                error: "Error reading groups file",
                details: error.message
            });
        }
    });
};
