aboutsummaryrefslogtreecommitdiffstats
path: root/ves-var-add.sh
blob: 7f0ee5ab0ef52b81eed5bd1c9ad080f02d18bb62 (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
#!/bin/sh

if [ -z ${XDG_DATA_HOME+x} ]; then
    ENV_DIR="$HOME/.local/share/ves/envs"
else
    ENV_DIR="$XDG_DATA_HOME/ves/envs"
fi

check_name() {
    if ! [ -f "$ENV_DIR/$1" ]; then
        printf "ERROR: Environment [%s] does not exist.\n" $1 > /dev/stderr
        exit 1
    fi

    if ! echo $1 | grep "^[[:alpha:][:digit:]_-]*$" > /dev/null; then
        printf "ERROR: Environment [%s] is invalid. Name must contain only letters, -, and _\n" $1 > /dev/stderr
        exit 1
    fi
}

ENV=""

while :; do
    case $1 in
        --env=*)
            ENV=$( echo $1 | cut -d "=" -f 2 )
            shift
            break
            ;;
        --)
            shift
            break
            ;;

        -?*)
            printf "ERROR: Invalid option [%s]\n" $1 > /dev/stderr
            exit 2
            ;;

        *)
            break
    esac
    shift
done

if ! [ -z $ENV ]; then
    check_name $ENV
elif ! [ -z $VES_ENV_NM ]; then
    # this check_name shouldn't be necessary, but I suppose someone
    # could always manually reassign the variable, so we'd better
    # check it.
    check_name $VES_ENV_NM
    ENV=$VES_ENV_NM
else
    printf "ERROR: No valid environment active or specified\n" > /dev/stderr
    exit 2
fi

if [ $# -lt 2 ]; then
    printf "ERROR: Insufficient arguments provided.\n"
    exit 2
fi

# Ah, bash would have made this so much nicer... alas
# if [ -z ${!1+x} ]; then ...
if eval [ -z \${$1+x} ]; then
    printf "ERROR: Specified variable [%s] does not exist in environment.\n" $1 > /dev/stderr
    printf "\tYou can create it with\n\t ves export %s\n " $1 > /dev/stderr
    exit 2
fi

# If we get down here, all is good. We can go ahead and prepend
# :$2 to the variable contained in $1. Again, no easy indirection,
# so we must use eval.
if eval [ -z \${$1} ]; then
  export $1=$2
else
    eval export "$1"="$2":\$"$1"
fi

# Perhaps we could use . to run this script from the main caller
# which could be set up as a shell function?
# That approach seems to work to modify the parent shell. Just
# gotta set up the main guy as a function.