summaryrefslogtreecommitdiff
path: root/packages/cern-scripts/resources/lib/activate.inc.sh
blob: 79bed6bdb5ca1a256436c26d41e3d1b012bc21fd (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
# non-interactive activate
 __activate_env() {
    for func in $(typeset -F | cut -f 3 -d ' ' | grep -E '^__env_'); do
        if [[ "$func" == "__env_$1" ]]; then
            $func
            echo "Activated $1"
            return 0
        fi
    done
    echo "Error: Environment not found $1" >&2
    return 1
}

# print all defined envs
list_envs() {
    for env in $(typeset -F | sed -n -e 's/^declare -f __env_//p'); do
        active=false
        for env_active in $ENV_ACTIVE; do
            if [ "$env_active" == "$env" ]; then
                active=true
            fi
        done
        if $active; then
            echo -n "${env}* "
        else
            echo -n "$env "
        fi
    done
    echo ""
}

plain_list_envs() {
    typeset -F | sed -n -e 's/^declare -f __env_//p'
}

# Interactive activate
activate() {
    err=false
    for env in $*; do
        if ! typeset -F | grep -q -E "^declare -f __env_${env}$"; then
            echo "Environment not defined: $env"
            err=true
        fi
    done
    if $err; then
        return 1
    fi

    for env in $*; do
        if typeset -F | grep -q -E "^declare -f __env_${env}$"; then
            export ENV_ACTIVE="$ENV_ACTIVE${ENV_ACTIVE:+ }$env"
            __env_${env}
        fi
    done
    echo "Active: $ENV_ACTIVE"
}

# initialization
for env_request in $ENV_ACTIVE; do
    __activate_env $env_request
done

# bash-completion for `activate'
_activate() {
    _init_completion -s || return
    COMPREPLY=( $(compgen -W "$(list_envs)" -- $cur) )
} && complete -F _activate activate