const fs = require('fs');

module.exports = function(app, checkApiKey) {
    app.post('/action/deletegroup', checkApiKey, (req, res) => {
        const { groupName } = req.body;
        if (!groupName) {
            return res.status(400).send('Group name is required');
        }
        const authzFilePath = '/etc/apache2/dav_svn.authz';  // Updated correct path
        fs.readFile(authzFilePath, 'utf8', (err, data) => {
            if (err) {
                return res.status(500).send(`Error reading authz file: ${err}`);
            }
            const groupRegex = new RegExp(`^${groupName}\\s*=.*$`, 'm');
            let updatedData = data;
            if (groupRegex.test(data)) {
                updatedData = updatedData.replace(groupRegex, '');
                updatedData = updatedData.replace(/^\s*[\r\n]/gm, '');
            } else {
                return res.status(404).send(`Group ${groupName} does not exist`);
            }
            fs.writeFile(authzFilePath, updatedData, 'utf8', (err) => {
                if (err) {
                    return res.status(500).send(`Error writing authz file: ${err}`);
                }
                res.send(`Group ${groupName} deleted successfully`);
            });
        });
    });
};
