summaryrefslogtreecommitdiffstats
path: root/nix-script
blob: 1c74471ee5f80d8c09d91b9e0f45d03dfa2ba59b (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env bash

#
# To be written
#
# Wrapper script for calling other scripts like so:
#
#   nix-script diff-generations 1 2
#
# So the "diff-generations" script looks like a command for "nix-script"
#

usage() {
    cat <<EOS >&2
    $(basename $0) [options] <command> <commandoptions>

    -l | --list-commands    List all available commands
    -v                      Be verbose
    -h                      Show this help and exit

    (c) 2015 Matthias Beyer
    GPLv2 licensed
EOS
}

LIST_COMMANDS=0
VERBOSE=0

source $(dirname ${BASH_SOURCE[0]})/nix-utils.sh

script_for() {
    echo "$(dirname ${BASH_SOURCE[0]})/nix-script-${1}.sh"
}

SHIFT_ARGS=0
shift_one_more() {
    SHIFT_ARGS=$(( SHIFT_ARGS + 1 ))
}

shift_n() {
    for n in `seq 0 $1`; do shift; done
    echo $*
}

all_commands() {
    find $(dirname ${BASH_SOURCE[0]}) -type f -name "nix-script-*.sh"
}

for cmd
do
    case $cmd in
    "--list-commands" )
        LIST_COMMANDS=1
        shift_one_more
        ;;

    "-l" )
        LIST_COMMANDS=1
        shift_one_more
        ;;

    "-v" )
        export VERBOSE=1
        stdout "Verbose now"
        shift_one_more
        ;;

    "-h" )
        usage
        exit 1
        ;;

    * )
        if [ ! -n $(script_for $cmd) ]
        then
            stderr "Unknown flag / command '$cmd'"
            exit 1
        else
            if [ -z "$COMMAND" ]
            then
                stdout "Found command: '$cmd'"
                COMMAND=$cmd
                shift_one_more
            fi
            break
        fi
    esac
done

if [ $LIST_COMMANDS -eq 1 ]
then
    stdout "Listing commands"
    for cmd in $(all_commands)
    do
        echo "$cmd" | sed 's,^\.\/nix-script-,,' | sed 's,\.sh$,,'
    done
    exit 0
fi

if [ -z "$COMMAND" ]
then
    stderr "No command given"
    exit 0
fi

stdout "Searching for script for '$COMMAND'"
SCRIPT=$(script_for $COMMAND)

if [ ! -f $SCRIPT ]
then
    stderr "Not available: $COMMAND -> $SCRIPT"
    exit 1
fi

if [[ ! -x $SCRIPT ]]
then
    stderr "Not executeable: $SCRIPT"
    exit 1
fi

stdout "Parsing args for '$COMMAND'"
SCRIPT_ARGS=$(shift_n $SHIFT_ARGS $*)

stdout "Calling: '$COMMAND $SCRIPT_ARGS'"
exec bash $SCRIPT $SCRIPT_ARGS