summaryrefslogtreecommitdiff
path: root/src/shblg.sh
blob: 8e436ba10dc90b4e3efeeea90481823ac8678634 (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
#!/bin/sh

INPUT_DIR=blog
OUTPUT_DIR=dist

usage () {
    printf "%s\n" "Usage: shblg [-i input_dir] [-o output_dir]"
    exit 1
}

# check if a file has changed since last generating
#
newer () {
    # TODO account for dependencies that have change
    [ ! -e "$2" ] || [ "$1" -nt "$2" ]
}

while getopts ":o:i:h" opt; do
    case "$opt" in
        o)
            OUTPUT_DIR="$OPTARG/"
            mkdir -p "$OUTPUT_DIR"
            OUTPUT_DIR="$(realpath "$OUTPUT_DIR")"
            ;;
        i)
            INPUT_DIR="$(realpath "$OPTARG")"
            ;;
        *) usage
            ;;
    esac
done

# process a file to 
process () {
    path="${1#"$INPUT_DIR"}"
    dirpath="${1%"${1##*/}"}"
    out_file="${OUTPUT_DIR}${path}"


    [ -d "$1" ] && {

        mkdir -p "$out_file"
        for f in "$1"/*; do
            process "$f"
        done

        return 0
    } || [ -x "$1" ] && {
        newer "$1" "$out_file" && (
                # execute the file
                cd $dirpath
                printf "#!%s\n" "$path"
                "$1" > "$out_file"
            )
        return 0
    } || {
        newer "$1" "$out_file" && (
            # just copy the file as is
            printf "%s\n" "$path"
            cp "$1" "$out_file"
        )
        return 0
    }
}

process "$INPUT_DIR"