const fs = require('fs');

module.exports = function(app, checkApiKey) {
    app.post('/action/setpermrepo', checkApiKey, async (req, res) => {
        try {
            const { repoName, userOrGroup, permission } = req.body;

            if (!repoName || !userOrGroup || !permission) {
                return res.status(400).json({ error: "Missing required parameters" });
            }

            // Validate permission value
            if (!['r', 'rw'].includes(permission)) {
                return res.status(400).json({ error: "Permission must be 'r' or 'rw'" });
            }

            await updateAuthzFile(repoName, userOrGroup, permission);
            res.json({ message: `Permissions updated successfully for ${userOrGroup} on ${repoName}` });

        } catch (error) {
            console.error('Error in setpermrepo:', error);
            res.status(500).json({ error: error.message });
        }
    });
};

async function updateAuthzFile(repoName, userOrGroup, permission) {
    const authzFilePath = '/etc/apache2/dav_svn.authz';

    try {
        if (!fs.existsSync(authzFilePath) || !fs.lstatSync(authzFilePath).isFile()) {
            throw new Error(`${authzFilePath} is not a valid file.`);
        }

        let data = fs.readFileSync(authzFilePath, 'utf8');
        const repoSection = `[/${repoName}]`;
        
        if (!data.includes(repoSection)) {
            // If repo section doesn't exist, create it
            data += `\n${repoSection}\n`;
        }

        // Split the file content into lines
        const lines = data.split('\n');
        let repoSectionIndex = lines.findIndex(line => line.trim() === repoSection);
        let sectionEnd = lines.slice(repoSectionIndex + 1).findIndex(line => line.startsWith('[')) + repoSectionIndex + 1;
        if (sectionEnd <= repoSectionIndex) sectionEnd = lines.length;

        // Format the user/group entry
        const entryPrefix = userOrGroup.startsWith('@') ? '' : '';
        const newEntry = `${entryPrefix}${userOrGroup} = ${permission}`;

        // Remove existing entry if it exists
        const existingEntryIndex = lines.findIndex((line, index) => {
            return index > repoSectionIndex && 
                   index < sectionEnd && 
                   line.trim().startsWith(`${entryPrefix}${userOrGroup} =`);
        });

        if (existingEntryIndex !== -1) {
            lines[existingEntryIndex] = newEntry;
        } else {
            lines.splice(repoSectionIndex + 1, 0, newEntry);
        }

        // Write back to file
        fs.writeFileSync(authzFilePath, lines.join('\n'));
        console.log(`Permissions updated for ${userOrGroup} on repository ${repoName}`);

    } catch (error) {
        console.error('Error updating authz file:', error);
        throw error;
    }
}
