import {
    $
} from 'bun';
import express from 'express'
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.json());
const port = 3000

app.get('/health', (req, res) => {
    res.json({
        healthy: true
    })
});

app.post('/update-certs', async (req, res) => {
    const domains: string[] = req.body.domains;
    if (domains.length == 1) {
        try {
            const text = await $`acme.sh \
                --issue \
                -k ec-384 \
                -w /var/www/html \
                -d ${domains[0]} \
                --reloadcmd "systemctl reload apache2.service" \
                --cert-file /etc/ssl/certs/ssl-certificate.pem \
                --fullchain-file /etc/ssl/certs/ssl-certficiate-chain.crt \
                --key-file /etc/ssl/private/ssl-cert.key \
                --server letsencrypt`

            res.send(text.stdout.toString());
        } catch (e) {
            console.log(e);
            return e;
        }
    }
    if (domains.length == 2) {
        try {
            const text = await $`acme.sh \
                --issue \
                --force \
                --debug \
                -w /var/www/html \
                -d ${domains[0]} \
                -d ${domains[1]} \
                --reloadcmd "systemctl reload apache2.service" \
                --cert-file /etc/ssl/certs/ssl-certificate.pem \
                --fullchain-file /etc/ssl/certs/ssl-certficiate-chain.crt \
                --key-file /etc/ssl/private/ssl-cert.key \
                --server https://api.buypass.com/acme/directory
                --days 170`

            res.send(text.stdout.toString());
        } catch (e) {
            console.log(e);
            return e;
        }
    }
});

app.post('/update-agent', async (req, res) => {
    await $`curl https://cdn.bennetgallein.de/products/hosted/agent.zip -o /root/agent/agent.zip`.text();
    await $`unzip -o agent.zip`.cwd('/root/agent').text();
    await $`systemctl restart agent.service`.text();
    return true;
});

app.post('/restart-agent', async (req, res) => {
    return $`systemctl restart agent.service`.text()
})

app.listen(port, () => {
    console.log(`BGA Hosted Agent listening on port ${port}`)
})