/* restricao.h — garante que comandos só executem em subdiretório direto de sisc */
#ifndef SISC_RESTRICAO_H
#define SISC_RESTRICAO_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>

static int raiz_sisc_por_executavel(char *out, size_t tam)
{
    char exe[PATH_MAX];
    ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
    if (n <= 0) return -1;
    exe[n] = '\0';
    char *slash = strrchr(exe, '/');
    if (!slash) return -1;
    *slash = '\0'; /* comandos */
    slash = strrchr(exe, '/');
    if (!slash) return -1;
    *slash = '\0'; /* core */
    slash = strrchr(exe, '/');
    if (!slash) return -1;
    *slash = '\0'; /* sisc */
    if (strlen(exe) + 1 > tam) return -1;
    snprintf(out, tam, "%s", exe);
    return 0;
}

static int restricao_verificar(const char *nome_comando)
{
    char raiz_sisc[PATH_MAX];
    if (raiz_sisc_por_executavel(raiz_sisc, sizeof(raiz_sisc)) != 0) {
        fprintf(stderr, "%s: executável fora de uma instalação SISC\n",
                nome_comando ? nome_comando : "sisc");
        return 1;
    }
    char cwd[PATH_MAX];
    if (!getcwd(cwd, sizeof(cwd))) {
        perror("sisc: getcwd");
        return 1;
    }
    size_t rl = strlen(raiz_sisc);
    if (strncmp(cwd, raiz_sisc, rl) != 0 || cwd[rl] != '/') {
        fprintf(stderr, "%s: deve ser executado dentro de um diretório SISC (não na raiz)\n",
                nome_comando ? nome_comando : "sisc");
        return 1;
    }
    return 0;
}

#endif
