import type { BUN_SQLITE_WGUI_CLIENTS, BUN_SQLITE_WGUI_CLIENT_RULES, BUN_SQLITE_WGUI_HOSTS, } from "@/db/types/db"; import BunSQLite from "@moduletrace/bun-sqlite"; import type { APIResponseObject } from "@moduletrace/bunext/types"; import type { TableType, User } from "@/src/types"; import manageWireguardHost from "./manage-wireguard-host"; import grabHostDirnames from "./grab-host-dir-names"; import grabClientDirnames from "./grab-client-dir-names"; import removeSubnetFirewallRules from "../firewall/remove-subnet-firewall-rules"; import { AppData } from "@/src/data/app-data"; import { execSync } from "node:child_process"; type Params = { host_id: number; user: User; }; export default async function deleteWireguardHost({ host_id, user, }: Params): Promise { try { const host_clients_res = await BunSQLite.select< BUN_SQLITE_WGUI_CLIENTS, TableType >({ table: "clients", query: { query: { host_id: { value: String(host_id) }, }, }, }); const clients = host_clients_res.payload || []; for (let i = 0; i < clients.length; i++) { const client = clients[i]; if (!client?.id) continue; await BunSQLite.delete({ table: "client_rules", query: { query: { client_id: { value: String(client.id) }, }, }, }); const { CLIENT_DIR } = grabClientDirnames({ client, host_id, }); try { execSync(`rm -rf ${CLIENT_DIR}`, { encoding: "utf-8" }); } catch {} await BunSQLite.delete({ table: "clients", targetId: client.id, }); } const { HOST_CONFIG_DIR, INTERFACE_NAME } = grabHostDirnames({ host: { id: host_id }, }); try { manageWireguardHost({ action: "down", host_id, }); } catch {} try { const host_res = await BunSQLite.select< BUN_SQLITE_WGUI_HOSTS, TableType >({ table: "hosts", targetId: host_id, }); const host = host_res.singleRes; if (host?.wg_ip_address) { const host_subnet = `${host.wg_ip_address .split(".") .slice(0, 3) .join(".")}.0/24`; const firewall_res = await removeSubnetFirewallRules({ subnet: host_subnet, listen_port: host.listen_port || AppData["DefaultWGListenPort"], }); if (!firewall_res.success) { console.log( `Warning removing firewall rules for host ${host_id} => ${firewall_res.msg}`, ); } } } catch (error: any) { console.log( `Warning removing firewall rules for host ${host_id} => ${error.message}`, ); } try { execSync(`rm -rf ${HOST_CONFIG_DIR}`, { encoding: "utf-8" }); } catch {} const del_host = await BunSQLite.sql({ sql: `DELETE FROM HOSTS WHERE id=?`, values: [host_id], }); return { success: true, msg: `Host ${host_id} deleted`, }; } catch (error: any) { return { success: false, msg: error.message, }; } }