const fs = require('fs');

module.exports = function(app, checkApiKey) {
    app.post('/action/newgroup', checkApiKey, (req, res) => {
        const { groupName, users } = req.body;
        if (!groupName || !users || !Array.isArray(users)) {
            return res.status(400).send('Group name and list of users are required');
        }
        const authzFilePath = '/etc/apache2/dav_svn.authz';  // Updated path
        fs.readFile(authzFilePath, 'utf8', (err, data) => {
            if (err) {
                return res.status(500).send(`Error reading authz file: ${err}`);
            }
            const groupSection = `${groupName} = ${users.join(', ')}`;
            let updatedData = data;
            const groupRegex = new RegExp(`^${groupName}\\s*=.*$`, 'm');
            if (groupRegex.test(data)) {
                updatedData = updatedData.replace(groupRegex, groupSection);
            } else {
                const groupsSectionRegex = /^\[groups\][\s\S]*?(?=\[|$)/m;
                if (groupsSectionRegex.test(data)) {
                    updatedData = updatedData.replace(groupsSectionRegex, `$&\n${groupSection}`);
                } else {
                    updatedData += `\n[groups]\n${groupSection}`;
                }
            }
            fs.writeFile(authzFilePath, updatedData, 'utf8', (err) => {
                if (err) {
                    return res.status(500).send(`Error writing authz file: ${err}`);
                }
                res.send(`Group ${groupName} created/updated successfully with users: ${users.join(', ')}`);
            });
        });
    });
};
