const { Client } = require('ssh2');
const fs = require('fs');
require('dotenv').config();

const config = {
    host: process.env.SSH_HOST,
    username: process.env.SSH_USER,
    port: 22,
};

console.log('--- SSH Connection Diagnostic ---');
console.log(`Target: ${config.username}@${config.host}`);
console.log(`Key Path: ${process.env.SSH_KEY_PATH || 'Not provided'}`);

// Fix common user mistake: providing public key instead of private
let privateKeyPath = process.env.SSH_KEY_PATH;
if (privateKeyPath && privateKeyPath.endsWith('.pub')) {
    console.warn('⚠️  WARNING: You provided a .pub key. Attempting to use the private key instead...');
    privateKeyPath = privateKeyPath.replace('.pub', '');
    console.log(`Trying: ${privateKeyPath}`);
}

if (privateKeyPath) {
    try {
        config.privateKey = fs.readFileSync(privateKeyPath);
        console.log('✅ Private key loaded.');
    } catch (err) {
        console.error('❌ Failed to read private key:', err.message);
        process.exit(1);
    }
} else if (process.env.SSH_PASSWORD) {
    console.log('Using SSH Password.');
    config.password = process.env.SSH_PASSWORD;
} else {
    console.error('❌ No Password or Key provided!');
    process.exit(1);
}

const conn = new Client();
conn.on('ready', () => {
    console.log('✅ SSH Connection Established!');
    conn.exec('uptime', (err, stream) => {
        if (err) throw err;
        stream.on('close', (code, signal) => {
            console.log('Command "uptime" executed successfully.');
            conn.end();
            process.exit(0);
        }).on('data', (data) => {
            console.log('Server Uptime: ' + data);
        }).stderr.on('data', (data) => {
            console.error('STDERR: ' + data);
        });
    });
}).on('error', (err) => {
    console.error('❌ Connection Failed:', err.message);
    if (err.message.includes('authentication')) {
        console.log('Hint: Check if the public key is in /root/.ssh/authorized_keys on the remote server.');
    }
    process.exit(1);
}).connect(config);
