const { execCommand, readFile } = require('./ssh_service');
require('dotenv').config();

const MAIN_CONFIG = '/etc/bacula/bacula-dir.conf';
const CLIENT_DIR = process.env.BACULA_CONF_DIR || '/etc/bacula/conf.d/clients';

(async () => {
    try {
        console.log(`--- Setting up Remote Structure ---`);
        console.log(`Target Dir: ${CLIENT_DIR}`);

        // 1. Create Directory
        console.log('Creating directory...');
        await execCommand(`mkdir -p "${CLIENT_DIR}"`);
        console.log('✅ Directory exists.');

        // 2. Check Permissions (Basic check)
        // Ensure bacula user can read it. usually root owns /etc/bacula, so root ssh is fine.

        // 3. Check Include in Main Config
        console.log(`Reading ${MAIN_CONFIG}...`);
        const configContent = await readFile(MAIN_CONFIG);

        // Check for the specific include directive. 
        // Bacula supports directory inclusion like @/path/to/dir since version 5.x+
        // However, standard include is often file based. Let's assume directory include works or check specific syntax.
        // Usually it is @"/etc/bacula/conf.d/clients"

        const includeLine = `@${CLIENT_DIR}`;
        const relativeInclude = `@${CLIENT_DIR.replace('/etc/bacula/', '')}`; // Sometimes relative paths are used

        if (configContent.includes(includeLine) || configContent.includes(relativeInclude)) {
            console.log('✅ Main config already includes the client directory.');
        } else {
            console.log('Populating config with include directive (Authorized)...');

            // 1. Append the include line
            await execCommand(`echo "${includeLine}" >> ${MAIN_CONFIG}`);
            console.log('✅ Added include directive to bacula-dir.conf');

            // 2. Reload Bacula
            console.log('Reloading Bacula Director...');
            try {
                // Try systemctl first
                await execCommand('systemctl reload bacula-director');
                console.log('✅ Bacula Director reloaded (systemctl).');
            } catch (e) {
                console.warn('⚠️ systemctl reload failed, trying service command...');
                // Fallback to service command
                await execCommand('service bacula-director reload');
                console.log('✅ Bacula Director reloaded (service).');
            }
        }

    } catch (err) {
        console.error('❌ Setup Failed:', err);
        process.exit(1);
    }
})();
