File size: 24,222 Bytes
6a64239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const fs = require('fs-extra');
const unzipper = require('unzipper');
const pm2 = require('pm2');
const { Server } = require('socket.io');
const http = require('http');
const bcrypt = require('bcryptjs');
const pidusage = require('pidusage');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

const PORT = process.env.PORT || 7860;

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/views', express.static(path.join(__dirname, 'views')));
app.use(session({
  secret: 'personal-bot-panel-secret-key-2024',
  resave: false,
  saveUninitialized: false,
  cookie: { 
    secure: false,
    maxAge: 24 * 60 * 60 * 1000 // 24 hours
  }
}));

// Simple auth middleware
const authMiddleware = (req, res, next) => {
  if (req.session && req.session.authenticated) {
    return next();
  }
  // If API request, send JSON error
  if (req.path.startsWith('/api/')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  // Otherwise redirect to login
  res.redirect('/login');
};

// Default admin credentials (change these in production)
const ADMIN_USERNAME = 'admin';
const ADMIN_PASSWORD = bcrypt.hashSync('admin123', 10);

// Login page route
app.get('/login', (req, res) => {
  if (req.session.authenticated) {
    return res.redirect('/');
  }
  res.sendFile(path.join(__dirname, 'public', 'login.html'));
});

// Login API
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  if (username === ADMIN_USERNAME && bcrypt.compareSync(password, ADMIN_PASSWORD)) {
    req.session.authenticated = true;
    return res.json({ success: true, redirect: '/' });
  }
  
  res.status(401).json({ error: 'Invalid credentials' });
});

// Logout
app.get('/api/logout', (req, res) => {
  req.session.destroy();
  res.json({ success: true });
});

// Protect all other routes
app.get('/', authMiddleware, (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/dashboard', authMiddleware, (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'dashboard.html'));
});

app.get('/filemanager', authMiddleware, (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'filemanager.html'));
});

app.get('/filemanager/:botName', authMiddleware, (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'filemanager.html'));
});

// Multer configuration for file uploads
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(__dirname, 'uploads');
    fs.ensureDirSync(uploadDir);
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 100 * 1024 * 1024 // 100MB limit
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype === 'application/zip' || 
        file.mimetype === 'application/x-zip-compressed' ||
        file.originalname.endsWith('.zip')) {
      cb(null, true);
    } else {
      cb(new Error('Only ZIP files are allowed'));
    }
  }
});

// API Routes

// Get all bots
app.get('/api/bots', authMiddleware, async (req, res) => {
  try {
    const botsDir = path.join(__dirname, 'bots');
    fs.ensureDirSync(botsDir);
    
    const botFolders = await fs.readdir(botsDir);
    const bots = [];
    
    for (const folder of botFolders) {
      const botPath = path.join(botsDir, folder);
      const stat = await fs.stat(botPath);
      
      if (stat.isDirectory()) {
        const configPath = path.join(botPath, 'bot-config.json');
        let config = {};
        
        if (await fs.pathExists(configPath)) {
          config = await fs.readJson(configPath);
        }
        
        // Get PM2 process info
        const processName = `bot-${folder}`;
        let status = 'offline';
        let pid = null;
        
        try {
          const processInfo = await new Promise((resolve, reject) => {
            pm2.describe(processName, (err, desc) => {
              if (err) return reject(err);
              resolve(desc);
            });
          });
          
          if (processInfo && processInfo.length > 0) {
            status = processInfo[0].pm2_env.status === 'online' ? 'online' : 'offline';
            pid = processInfo[0].pid;
          }
        } catch (err) {
          // Process doesn't exist, keep offline status
        }
        
        let cpuUsage = 0;
        let memoryUsage = 0;
        
        if (pid) {
          try {
            const stats = await pidusage(pid);
            cpuUsage = stats.cpu.toFixed(2);
            memoryUsage = (stats.memory / 1024 / 1024).toFixed(2); // MB
          } catch (err) {
            // Process may have ended
          }
        }
        
        bots.push({
          name: folder,
          type: config.type || 'unknown',
          mainFile: config.mainFile || 'unknown',
          status: status,
          pid: pid,
          cpu: cpuUsage,
          memory: memoryUsage,
          uptime: processInfo && processInfo.length > 0 ? processInfo[0].pm2_env.pm_uptime : null,
          restartCount: processInfo && processInfo.length > 0 ? processInfo[0].pm2_env.restart_time : 0,
          createdAt: stat.birthtime
        });
      }
    }
    
    res.json({ bots });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Upload bot
app.post('/api/bots/upload', authMiddleware, upload.single('bot'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'No file uploaded' });
    }
    
    const zipPath = req.file.path;
    const botName = req.body.name || path.basename(req.file.originalname, '.zip');
    
    // Validate bot name
    if (!/^[a-zA-Z0-9_-]+$/.test(botName)) {
      await fs.remove(zipPath);
      return res.status(400).json({ error: 'Invalid bot name. Use only letters, numbers, hyphens, and underscores.' });
    }
    
    const botDir = path.join(__dirname, 'bots', botName);
    
    // Check if bot already exists
    if (await fs.pathExists(botDir)) {
      await fs.remove(zipPath);
      return res.status(400).json({ error: 'Bot with this name already exists' });
    }
    
    // Extract ZIP
    await fs.ensureDir(botDir);
    
    await new Promise((resolve, reject) => {
      fs.createReadStream(zipPath)
        .pipe(unzipper.Extract({ path: botDir }))
        .on('close', resolve)
        .on('error', reject);
    });
    
    // Clean up uploaded zip
    await fs.remove(zipPath);
    
    // Detect bot type
    const files = await fs.readdir(botDir);
    let botType = 'unknown';
    let mainFile = null;
    
    // Check for Node.js project
    if (files.includes('package.json')) {
      botType = 'nodejs';
      const packageJson = await fs.readJson(path.join(botDir, 'package.json'));
      mainFile = packageJson.main || 'index.js';
      
      // Install npm dependencies
      const { exec } = require('child_process');
      exec('npm install', { cwd: botDir }, (err, stdout, stderr) => {
        if (err) {
          console.error(`npm install error for ${botName}:`, stderr);
        }
      });
    }
    // Check for Python project
    else if (files.includes('requirements.txt') || files.includes('main.py')) {
      botType = 'python';
      mainFile = files.includes('main.py') ? 'main.py' : files.find(f => f.endsWith('.py'));
      
      // Install pip dependencies
      if (files.includes('requirements.txt')) {
        const { exec } = require('child_process');
        exec('pip install -r requirements.txt', { cwd: botDir }, (err, stdout, stderr) => {
          if (err) {
            console.error(`pip install error for ${botName}:`, stderr);
          }
        });
      }
    }
    // Detect main file
    else {
      mainFile = files.find(f => f.endsWith('.js') || f.endsWith('.py'));
      if (mainFile && mainFile.endsWith('.js')) {
        botType = 'nodejs';
      } else if (mainFile && mainFile.endsWith('.py')) {
        botType = 'python';
      }
    }
    
    // Save bot configuration
    const config = {
      name: botName,
      type: botType,
      mainFile: mainFile,
      createdAt: new Date().toISOString()
    };
    
    await fs.writeJson(path.join(botDir, 'bot-config.json'), config);
    
    res.json({ success: true, bot: { name: botName, type: botType, mainFile: mainFile } });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Start bot
app.post('/api/bots/:name/start', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const botDir = path.join(__dirname, 'bots', botName);
    
    if (!await fs.pathExists(botDir)) {
      return res.status(404).json({ error: 'Bot not found' });
    }
    
    const configPath = path.join(botDir, 'bot-config.json');
    if (!await fs.pathExists(configPath)) {
      return res.status(400).json({ error: 'Bot configuration not found' });
    }
    
    const config = await fs.readJson(configPath);
    const processName = `bot-${botName}`;
    
    // Build PM2 start command
    let script = '';
    let interpreter = '';
    let args = [];
    
    if (config.type === 'nodejs') {
      script = path.join(botDir, config.mainFile || 'index.js');
      interpreter = 'node';
    } else if (config.type === 'python') {
      script = path.join(botDir, config.mainFile || 'main.py');
      interpreter = 'python3';
    }
    
    // Connect to PM2 and start the process
    await new Promise((resolve, reject) => {
      pm2.connect((err) => {
        if (err) return reject(err);
        
        pm2.start({
          name: processName,
          script: script,
          interpreter: interpreter,
          args: args,
          cwd: botDir,
          autorestart: true,
          max_restarts: 10,
          watch: false,
          env: {
            NODE_ENV: 'production',
            BOT_NAME: botName
          }
        }, (err, apps) => {
          if (err) {
            pm2.disconnect();
            return reject(err);
          }
          
          // Save PM2 process list
          pm2.save((err) => {
            pm2.disconnect();
            if (err) return reject(err);
            resolve(apps);
          });
        });
      });
    });
    
    // Notify via socket
    io.emit('botStatusChanged', { name: botName, status: 'online' });
    
    res.json({ success: true, message: 'Bot started successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Stop bot
app.post('/api/bots/:name/stop', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const processName = `bot-${botName}`;
    
    await new Promise((resolve, reject) => {
      pm2.connect((err) => {
        if (err) return reject(err);
        
        pm2.stop(processName, (err) => {
          if (err) {
            pm2.disconnect();
            return reject(err);
          }
          
          pm2.save((err) => {
            pm2.disconnect();
            if (err) return reject(err);
            resolve();
          });
        });
      });
    });
    
    io.emit('botStatusChanged', { name: botName, status: 'offline' });
    
    res.json({ success: true, message: 'Bot stopped successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Restart bot
app.post('/api/bots/:name/restart', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const processName = `bot-${botName}`;
    
    await new Promise((resolve, reject) => {
      pm2.connect((err) => {
        if (err) return reject(err);
        
        pm2.restart(processName, (err) => {
          if (err) {
            pm2.disconnect();
            return reject(err);
          }
          
          pm2.save((err) => {
            pm2.disconnect();
            if (err) return reject(err);
            resolve();
          });
        });
      });
    });
    
    io.emit('botStatusChanged', { name: botName, status: 'online' });
    
    res.json({ success: true, message: 'Bot restarted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Delete bot
app.delete('/api/bots/:name', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const botDir = path.join(__dirname, 'bots', botName);
    const processName = `bot-${botName}`;
    
    // Stop and delete from PM2 first
    await new Promise((resolve, reject) => {
      pm2.connect((err) => {
        if (err) return reject(err);
        
        pm2.delete(processName, (err) => {
          if (err && !err.message.includes('not found')) {
            pm2.disconnect();
            return reject(err);
          }
          
          pm2.save((err) => {
            pm2.disconnect();
            if (err) return reject(err);
            resolve();
          });
        });
      });
    });
    
    // Remove bot directory
    await fs.remove(botDir);
    
    io.emit('botDeleted', { name: botName });
    
    res.json({ success: true, message: 'Bot deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Get bot logs
app.get('/api/bots/:name/logs', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const processName = `bot-${botName}`;
    
    const logs = await new Promise((resolve, reject) => {
      pm2.connect((err) => {
        if (err) return reject(err);
        
        pm2.describe(processName, (err, desc) => {
          if (err) {
            pm2.disconnect();
            return reject(err);
          }
          
          if (!desc || desc.length === 0) {
            pm2.disconnect();
            return resolve('');
          }
          
          const logPath = desc[0].pm2_env.pm_out_log_path;
          pm2.disconnect();
          
          if (logPath && fs.existsSync(logPath)) {
            const logContent = fs.readFileSync(logPath, 'utf8');
            // Return last 1000 lines
            const lines = logContent.split('\n');
            const recentLines = lines.slice(-1000);
            resolve(recentLines.join('\n'));
          } else {
            resolve('');
          }
        });
      });
    });
    
    res.json({ logs: logs || '' });
  } catch (error) {
    // If PM2 process doesn't exist, try reading from a potential log file
    try {
      const logPath = path.join(process.env.HOME || '/tmp', '.pm2', 'logs', `bot-${req.params.name}-out.log`);
      if (await fs.pathExists(logPath)) {
        const content = await fs.readFile(logPath, 'utf8');
        return res.json({ logs: content });
      }
    } catch (err) {
      // Ignore
    }
    res.json({ logs: '' });
  }
});

// Get file list for a bot
app.get('/api/bots/:name/files', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const botDir = path.join(__dirname, 'bots', botName);
    
    if (!await fs.pathExists(botDir)) {
      return res.status(404).json({ error: 'Bot not found' });
    }
    
    const files = await listFiles(botDir, botDir);
    res.json({ files });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Read file content
app.get('/api/bots/:name/files/read', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const filePath = req.query.path;
    
    if (!filePath) {
      return res.status(400).json({ error: 'File path required' });
    }
    
    // Prevent path traversal
    const botDir = path.join(__dirname, 'bots', botName);
    const fullPath = path.join(botDir, filePath);
    
    if (!fullPath.startsWith(botDir)) {
      return res.status(403).json({ error: 'Access denied' });
    }
    
    if (!await fs.pathExists(fullPath)) {
      return res.status(404).json({ error: 'File not found' });
    }
    
    const stat = await fs.stat(fullPath);
    if (stat.isDirectory()) {
      const files = await listFiles(fullPath, botDir);
      return res.json({ type: 'directory', files });
    }
    
    const content = await fs.readFile(fullPath, 'utf8');
    res.json({ type: 'file', content, size: stat.size });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Save file content
app.post('/api/bots/:name/files/save', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const { path: filePath, content } = req.body;
    
    if (!filePath) {
      return res.status(400).json({ error: 'File path required' });
    }
    
    const botDir = path.join(__dirname, 'bots', botName);
    const fullPath = path.join(botDir, filePath);
    
    if (!fullPath.startsWith(botDir)) {
      return res.status(403).json({ error: 'Access denied' });
    }
    
    await fs.writeFile(fullPath, content);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Delete file
app.delete('/api/bots/:name/files/delete', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const filePath = req.query.path;
    
    if (!filePath) {
      return res.status(400).json({ error: 'File path required' });
    }
    
    const botDir = path.join(__dirname, 'bots', botName);
    const fullPath = path.join(botDir, filePath);
    
    if (!fullPath.startsWith(botDir)) {
      return res.status(403).json({ error: 'Access denied' });
    }
    
    await fs.remove(fullPath);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Create directory
app.post('/api/bots/:name/files/mkdir', authMiddleware, async (req, res) => {
  try {
    const botName = req.params.name;
    const { path: dirPath, name } = req.body;
    
    const botDir = path.join(__dirname, 'bots', botName);
    const fullPath = path.join(botDir, dirPath || '', name);
    
    if (!fullPath.startsWith(botDir)) {
      return res.status(403).json({ error: 'Access denied' });
    }
    
    await fs.ensureDir(fullPath);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Upload file to bot
app.post('/api/bots/:name/files/upload', authMiddleware, upload.single('file'), async (req, res) => {
  try {
    const botName = req.params.name;
    const uploadPath = req.body.path || '';
    
    const botDir = path.join(__dirname, 'bots', botName);
    const destDir = path.join(botDir, uploadPath);
    const destPath = path.join(destDir, req.file.originalname);
    
    if (!destPath.startsWith(botDir)) {
      await fs.remove(req.file.path);
      return res.status(403).json({ error: 'Access denied' });
    }
    
    await fs.ensureDir(destDir);
    await fs.move(req.file.path, destPath, { overwrite: true });
    
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Get system info
app.get('/api/system/info', authMiddleware, async (req, res) => {
  try {
    const os = require('os');
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    const usedMem = totalMem - freeMem;
    
    res.json({
      platform: os.platform(),
      arch: os.arch(),
      cpus: os.cpus().length,
      totalMemory: (totalMem / 1024 / 1024 / 1024).toFixed(2),
      usedMemory: (usedMem / 1024 / 1024 / 1024).toFixed(2),
      freeMemory: (freeMem / 1024 / 1024 / 1024).toFixed(2),
      uptime: os.uptime(),
      nodeVersion: process.version
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Helper function to list files recursively
async function listFiles(dir, baseDir) {
  const files = await fs.readdir(dir);
  const fileList = [];
  
  for (const file of files) {
    if (file === 'node_modules' || file === '__pycache__' || file.startsWith('.')) {
      continue;
    }
    
    const fullPath = path.join(dir, file);
    const relativePath = path.relative(baseDir, fullPath);
    const stat = await fs.stat(fullPath);
    
    fileList.push({
      name: file,
      path: relativePath,
      type: stat.isDirectory() ? 'directory' : 'file',
      size: stat.size,
      modifiedAt: stat.mtime
    });
  }
  
  return fileList;
}

// Socket.io connection for realtime logs
io.on('connection', (socket) => {
  console.log('Client connected');
  
  socket.on('subscribe-logs', async (botName) => {
    const processName = `bot-${botName}`;
    
    // Send initial logs
    try {
      const logs = await new Promise((resolve) => {
        pm2.connect((err) => {
          if (err) {
            resolve('');
            return;
          }
          
          pm2.describe(processName, (err, desc) => {
            pm2.disconnect();
            if (err || !desc || desc.length === 0) {
              resolve('');
              return;
            }
            
            const logPath = desc[0].pm2_env.pm_out_log_path;
            if (logPath && fs.existsSync(logPath)) {
              const content = fs.readFileSync(logPath, 'utf8');
              const lines = content.split('\n').slice(-100);
              resolve(lines.join('\n'));
            } else {
              resolve('');
            }
          });
        });
      });
      
      socket.emit('logs-update', { botName, logs });
    } catch (err) {
      console.error('Error fetching logs:', err);
    }
    
    // Set up log watching
    const watcher = setInterval(async () => {
      try {
        const logs = await new Promise((resolve) => {
          pm2.connect((err) => {
            if (err) {
              resolve('');
              return;
            }
            
            pm2.describe(processName, (err, desc) => {
              pm2.disconnect();
              if (err || !desc || desc.length === 0) {
                resolve('');
                return;
              }
              
              const logPath = desc[0].pm2_env.pm_out_log_path;
              if (logPath && fs.existsSync(logPath)) {
                const content = fs.readFileSync(logPath, 'utf8');
                resolve(content);
              } else {
                resolve('');
              }
            });
          });
        });
        
        socket.emit('logs-update', { botName, logs });
      } catch (err) {
        console.error('Error watching logs:', err);
      }
    }, 2000);
    
    socket.on('disconnect', () => {
      clearInterval(watcher);
    });
  });
  
  socket.on('disconnect', () => {
    console.log('Client disconnected');
  });
});

// Initialize PM2 and restore saved processes
async function initializePM2() {
  return new Promise((resolve, reject) => {
    pm2.connect((err) => {
      if (err) {
        console.error('Error connecting to PM2:', err);
        return reject(err);
      }
      
      // Try to resurrect previously saved processes
      pm2.resurrect((err) => {
        if (err) {
          console.log('No previous processes to restore or error restoring:', err.message);
        } else {
          console.log('Restored previously saved processes');
        }
        
        pm2.save((err) => {
          if (err) {
            console.error('Error saving PM2 process list:', err);
          }
          pm2.disconnect();
          resolve();
        });
      });
    });
  });
}

// Start server
async function startServer() {
  try {
    await initializePM2();
    
    server.listen(PORT, '0.0.0.0', () => {
      console.log(`Bot Hosting Panel running on port ${PORT}`);
      console.log(`Open http://localhost:${PORT} in your browser`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

startServer();