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

module.exports = function(app, getToken) {
    app.post('/action/login', (req, res) => {
        const { username, password } = req.body;

        if (!username || !password) {
            return res.status(400).send('Username and password are required');
        }

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

        try {
            const passwdContent = fs.readFileSync(passwdFilePath, 'utf8');
            const userLine = passwdContent.split('\n').find(line => line.startsWith(`${username}:`));
            
            if (!userLine) {
                return res.status(401).send('Invalid credentials');
            }

            const storedHash = userLine.split(':')[1];
            const calculatedHash = apacheMd5(password, storedHash);

            if (storedHash !== calculatedHash) {
                return res.status(401).send('Invalid credentials');
            }

            const authzContent = fs.readFileSync(authzFilePath, 'utf8');
            const lines = authzContent.split('\n');
            let isInAdminGroup = false;
            let inGroupSection = false;

            for (const line of lines) {
                if (line.trim() === '[groups]') {
                    inGroupSection = true;
                    continue;
                }
                if (inGroupSection && line.startsWith('admin =')) {
                    const groupMembers = line.split('=')[1].trim().split(',').map(m => m.trim());
                    isInAdminGroup = groupMembers.includes(username);
                    break;
                }
            }

            if (isInAdminGroup) {
                res.json({
                    authenticated: true,
                    isAdmin: true,
                    token: getToken()
                });
            } else {
                res.json({
                    authenticated: true,
                    isAdmin: false
                });
            }

        } catch (error) {
            res.status(500).send('Authentication failed');
        }
    });
};