const fs = require('fs');
const apacheMd5 = require('apache-md5');

module.exports = function(app, checkApiKey) {
    app.post('/action/changepassword', checkApiKey, (req, res) => {
        const { username, newPassword } = req.body;

        // Vérification des paramètres
        if (!username || !newPassword) {
            return res.status(400).send('Username and new password are required');
        }

        const passwdFilePath = '/etc/apache2/dav_svn.passwd';

        // Lire le fichier passwd
        fs.readFile(passwdFilePath, 'utf8', (err, data) => {
            if (err) {
                return res.status(500).send(`Error reading passwd file: ${err}`);
            }

            const lines = data.split('\n');
            let userFound = false;
            const newLines = lines.map(line => {
                if (line.startsWith(`${username}:`)) {
                    userFound = true;
                    const hashedPassword = apacheMd5(newPassword);
                    return `${username}:${hashedPassword}`;
                }
                return line;
            });

            if (!userFound) {
                return res.status(404).send(`User ${username} not found`);
            }

            // Écrire les modifications dans le fichier passwd
            fs.writeFile(passwdFilePath, newLines.join('\n'), 'utf8', (err) => {
                if (err) {
                    return res.status(500).send(`Error updating passwd file: ${err}`);
                }
                res.send(`Password for user ${username} changed successfully`);
            });
        });
    });
};
