const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

module.exports = function(app, checkApiKey) {
    app.post('/action/newrepo', checkApiKey, (req, res) => {
        const repoName = req.body.repoName;
        if (!repoName) {
            return res.status(400).send('Repo name is required');
        }
        const repoPath = `/var/svn/${repoName}`;
        const cmd = `svnadmin create ${repoPath}`;
        exec(cmd, async (err, stdout, stderr) => {
            if (err) {
                return res.status(500).send(`Error creating repo: ${stderr}`);
            }
            try {
                await setPermissions(repoName);
                await updateAuthzFile(repoName);
                res.send({
                    message: `Repository ${repoName} created successfully`,
                    apiKey: process.env.API_KEY
                });
            } catch (error) {
                res.status(500).send(`Error setting permissions: ${error}`);
            }
        });
    });

    async function setPermissions(repo) {
        try {
            const svnReposPath = `/var/svn/${repo}`;
            const chmodCmd = `chmod -R 775 ${svnReposPath}`;
            const chownCmd = `chown -R www-data:www-data ${svnReposPath}`;
            await executeCommand(chmodCmd);
            await executeCommand(chownCmd);
            console.log('Permissions updated successfully.');
        } catch (error) {
            console.error('Error setting permissions:', error);
            throw error;
        }
    }

    

    function executeCommand(cmd) {
        return new Promise((resolve, reject) => {
            exec(cmd, (error, stdout, stderr) => {
                if (error) {
                    reject(`Error executing command: ${cmd}\n${stderr}`);
                } else {
                    resolve(stdout);
                }
            });
        });
    }
};
