import express, { Request, Response } from 'express';
import { exec } from 'child_process';
import { promisify } from 'util';

const router = express.Router();
const promiseExec = promisify(exec);

router.get('/cwd', async (req: Request, res: Response) => {
  const { pid } = req.query;
  try {
    const { stdout } = await promiseExec(`lsof -a -p ${pid} -d cwd -Fn | tail -1 | sed 's/.//'`);
    const cwd = stdout.trim();
    // @ts-ignore
    res.success(cwd);
  } catch (error) {
    // @ts-ignore
    res.fail('Failed to retrieve current working directory');
  }
});

export default router;
