const fs = require('fs');

module.exports = function(app, checkApiKey) {
    app.post('/action/addingroup', checkApiKey, (req, res) => {
        const { groupName, username } = req.body;
        
        if (!groupName || !username) {
            return res.status(400).send('Group name and username are required');
        }

        const authzFilePath = '/etc/apache2/dav_svn.authz';

        fs.readFile(authzFilePath, 'utf8', (err, data) => {
            if (err) {
                return res.status(500).send(`Error reading authz file: ${err}`);
            }

            const lines = data.split('\n');
            let groupLineIndex = -1;
            let groupLine = '';

            // Find the group line
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].startsWith(groupName + ' =')) {
                    groupLineIndex = i;
                    groupLine = lines[i];
                    break;
                }
            }

            if (groupLineIndex === -1) {
                return res.status(404).send(`Group ${groupName} not found`);
            }

            // Parse existing users and add new user
            const users = groupLine.split('=')[1].trim().split(',').map(u => u.trim());
            if (!users.includes(username)) {
                users.push(username);
                lines[groupLineIndex] = `${groupName} = ${users.join(', ')}`;

                fs.writeFile(authzFilePath, lines.join('\n'), 'utf8', (err) => {
                    if (err) {
                        return res.status(500).send(`Error updating authz file: ${err}`);
                    }
                    res.send(`User ${username} added to group ${groupName} successfully`);
                });
            } else {
                res.send(`User ${username} is already in group ${groupName}`);
            }
        });
    });
};
