"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const child_process_1 = require("child_process");
async function bootstrap() {
    const envPath = path.join(__dirname, '../../.env');
    if (!fs.existsSync(envPath)) {
        console.error('.env file not found');
        process.exit(1);
    }
    const envContent = fs.readFileSync(envPath, 'utf8');
    const env = {};
    envContent.split('\n').forEach((line) => {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#'))
            return;
        const parts = trimmed.split('=');
        if (parts.length >= 2) {
            const key = parts[0].trim();
            const value = parts.slice(1).join('=').trim();
            env[key] = value;
        }
    });
    const dbHost = env.DB_HOST || '127.0.0.1';
    const dbPort = env.DB_PORT || '3306';
    const dbUser = env.DB_USERNAME;
    const dbPass = env.DB_PASSWORD;
    const dbName = env.DB_NAME;
    if (!dbUser || !dbPass || !dbName) {
        console.error('Missing DB credentials in .env');
        process.exit(1);
    }
    let mysqldumpPath = 'mysqldump';
    try {
        (0, child_process_1.execSync)('which mysqldump', { stdio: 'ignore' });
    }
    catch {
        const alternatives = [
            '/opt/homebrew/bin/mysqldump',
            '/usr/local/mysql/bin/mysqldump',
            '/usr/local/bin/mysqldump'
        ];
        for (const alt of alternatives) {
            if (fs.existsSync(alt)) {
                mysqldumpPath = alt;
                break;
            }
        }
    }
    const dateStr = new Date().toISOString().split('T')[0];
    const backupDir = path.join(__dirname, '../../backups');
    if (!fs.existsSync(backupDir)) {
        fs.mkdirSync(backupDir, { recursive: true });
    }
    const backupFile = path.join(backupDir, `${dbName}_${dateStr}.sql`);
    console.log(`Backing up database "${dbName}" to ${backupFile}...`);
    const cmd = `"${mysqldumpPath}" --skip-ssl -h ${dbHost} -P ${dbPort} -u ${dbUser} -p'${dbPass}' ${dbName} > "${backupFile}"`;
    try {
        (0, child_process_1.execSync)(cmd, { stdio: 'inherit' });
        console.log('Database backup completed successfully.');
    }
    catch (error) {
        console.error('Failed to run mysqldump:', error);
        process.exit(1);
    }
}
bootstrap();
//# sourceMappingURL=db-backup.js.map