'use strict'; const express = require('express'); const path = require('path'); const { initDb, closeDb } = require('./db'); const { ensureServerKeys } = require('./crypto'); const { loadConfig } = require('./config'); const authRoutes = require('./routes/auth'); const filesRoutes = require('./routes/files'); const adminRoutes = require('./routes/admin'); const app = express(); app.use(express.json({ limit: '50mb' })); app.use(express.static(path.join(__dirname, '../public'))); app.use('/api/auth', authRoutes); app.use('/api/files', filesRoutes); app.use('/api/admin', adminRoutes); // SPA catch-all (only for non-API routes) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')); }); // Exposed so the shutdown route can trigger a graceful stop. function shutdown(server) { server.close(() => { closeDb(); process.exit(0); }); // Force-exit after 5 s if connections don't drain in time. setTimeout(() => { closeDb(); process.exit(0); }, 5000).unref(); } function start() { initDb(); ensureServerKeys(); const config = loadConfig(); const port = config.port || 3000; const server = app.listen(port, '0.0.0.0', () => { console.log(`File manager running at http://localhost:${port}`); }); // Give the admin route access to the server handle for graceful shutdown. app.set('server', server); app.set('shutdown', () => shutdown(server)); } try { start(); } catch (err) { console.error('Failed to start server:', err); process.exit(1); }