summaryrefslogtreecommitdiff
path: root/core/hook.c
blob: 9e90b2b1e07de2c260f262063a1f3c3d3d2dbcf2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
 * Copyright (c) 2026, Chloe M., et al.
 * Provided under the BSD-3 clause.
 */

#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "bop/hook.h"

/* Shell we use by default */
#define DEFAULT_SHELL_PATH "/bin/sh"

/*
 * Execute the shell for a specific shell script
 *
 * @script_path:  Path of shell script
 */
static void
exec_shell_for(const char *script_path)
{
    char *shell_path;

    if (script_path == NULL) {
        return;
    }

    /*
     * We will attempt to use the current shell but if we cannot determine it,
     * we will then fallback to the default shell path.
     */
    shell_path = getenv("SHELL");
    if (shell_path == NULL) {
        shell_path = DEFAULT_SHELL_PATH;
        printf("warning: could not determine shell\n");
        printf("warning: falling back to '%s'\n", shell_path);
    }

    execl(shell_path, shell_path, script_path, NULL);
}

/*
 * Run a shell hook with POSIX sh
 *
 * XXX: Maybe support '#!/bin/xxx'?
 */
int
bop_shell_hook(const char *hook_path)
{
    pid_t child;
    int status = 0;

    if (hook_path == NULL) {
        return -1;
    }

    child = fork();
    if (child == 0) {
        exec_shell_for(hook_path);
    } else {
        waitpid(child, &status, 0);
    }

    if (status != 0) {
        printf("error: failure in '%s'\n", hook_path);
    }

    return status;
}