#!/usr/bin/env bash
# Remove an installed Teletraan module.  Usage: remove-module.sh <module-name> [--delete-files]
set -euo pipefail

MODULE="${1:-}"
if [ -z "$MODULE" ]; then
  echo "Usage: $0 <module-name> [--delete-files]" >&2
  exit 1
fi

DELETE_FILES=false
if [ "${2:-}" = "--delete-files" ]; then
  DELETE_FILES=true
fi

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRAMEWORK_ROOT="$(dirname "$DIR")"
CONFIG="$FRAMEWORK_ROOT/config/system.json"

if [ ! -f "$CONFIG" ]; then
  echo "Error: system.json not found at $CONFIG" >&2
  exit 1
fi

node --input-type=module <<EOF
import { removeModule } from '$FRAMEWORK_ROOT/installer/modules.js';
import { readFileSync } from 'node:fs';

const systemConfig = JSON.parse(readFileSync('$CONFIG', 'utf8'));
const removeFiles = $DELETE_FILES;

removeModule('$MODULE', systemConfig, removeFiles);
console.log("Module '$MODULE' has been removed.");
EOF
