bashhelper.sh 5.89 KB
Newer Older
1 2 3 4 5 6 7 8 9
#!/bin/bash
#
#    Copyright 2015-today www.webis.de
#
#    Bashhelper functions.
#
#    Project general
#    Author: Steve Göring
#
10 11
webiscmd_libs_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
webiscmdrootpath="$(${webiscmd_libs_dir}/readlink-f.py $webiscmd_libs_dir/../)/"
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

#
#    Logging macros,
#        e.g. for errors, warnings, information, debug, ...
#

#
#    Printout error to stderr.
#
logError() {
    echo -e "\033[91m[ERROR]\033[0m $@ " 1>&2;
}

#
#    Printout info message.
#
logInfo() {
29
    echo -e "\033[92m[INFO ]\033[0m $@" 1>&2;
30 31 32 33 34 35
}

#
#    Printout debug info if debug enabled.
#
logDebug() {
36
    $(is_var_set WEBIS_DEBUG) && echo -e "\033[94m[DEBUG]\033[0m $@" 1>&2 || true;
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
}

#
#    Printout warning.
#
logWarn() {
    echo -e "\033[96m[WARN ]\033[0m $@" 1>&2;
}

#
#    Printout todo things.
#
logTodo() {
    echo -e "\033[35m[TODO ]\033[0m $@" 1>&2;
}

logCall() {
    echo "$(date) : $@" >> "$_LOG_FILE"
}

#
#    Checks if needed tools are available.
#
#    \params $@ list of tools
#    Example call:
#        checktools "bash nano"
#
check_tools() {
    for tool in $@; do
        which $tool > /dev/null

        if [[ "$?" -ne 0 ]]; then
            logError "$tool is not installed."
            exit 1
        fi
    done
    logDebug "Each needed tool ($@) is installed."
}

#
#    Reads a password from stdin.
#
#    \params $1 promt message
#    \params $2 name of result variable
#    Example call:
#        read_password "Please insert your secret password ;)" passwordvar
#
read_password() {
    __resultvar="$2"
    logInfo "$1"
    read -s pw
    eval "$__resultvar=\"$pw\""
}

#
#    Reads (y)es or (n) from stdin, exit if 'y' was not choosen.
#
Janek Bevendorff's avatar
Janek Bevendorff committed
94 95
#    \params $1 prompt message
#    \params $2 default ("y" or "n"), leave empty for no default
96
#    Example call:
Janek Bevendorff's avatar
Janek Bevendorff committed
97
#        yes_no_prompt "Is bash not wonderful?" && echo "Yes" || echo "no"
98
#
99
yes_no_prompt() {
Janek Bevendorff's avatar
Janek Bevendorff committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    if [ "y" == "$2" ]; then
        echo -n "$1 [Y/n] "
        read yesno
        if [ "$yesno" == "" ] || [ "$yesno" == "y" ] || [ "$yesno" == "Y" ]; then
            return 0
        fi
    elif [ "n" == "$2" ]; then
        echo -n "$1 [y/N] "
        read yesno
        if [ "$yesno" == "y" ] || [ "$yesno" == "Y" ]; then
            return 0;
        fi
    else
        echo -n "$1 [y/n] "
        read yesno
115

Janek Bevendorff's avatar
Janek Bevendorff committed
116 117 118 119 120 121
        if [ "$yesno" == "y" ] || [ "$yesno" == "Y" ]; then
            return 0
        elif [ "$yesno" == "n" ] || [ "$yesno" == "Y" ]; then
            return 1
        fi
        logError "Answer either 'y' or 'n'."
122 123 124
        exit 1
    fi

Janek Bevendorff's avatar
Janek Bevendorff committed
125
    return 1
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
}

#
#    SSH key exchange.
#
#    \params $1 user at host
#    \params $2 user password
#    Example call:
#        ssh_key_exchange "myuser@mypc" "mysecretpassword"
#
ssh_key_exchange() {
    userathost="$1"
    pw="$2"
    # create a ssh key if there is no one
    if [ ! -f ~/.ssh/id_rsa ]; then
        logInfo "Rsa key does not exist, create one."
        ssh-keygen -N "" -f ~/.ssh/id_rsa
    fi
    cat ~/.ssh/id_rsa.pub | sshpass -p "$pw" ssh "$userathost" \
        -o UserKnownHostsFile=/dev/null \
        -o StrictHostKeyChecking=no \
        -o LogLevel=error \
        "(cat > tmp.pubkey ; \
            mkdir -p .ssh ; \
            touch .ssh/authorized_keys ; \
            sed -i.bak -e '/$(awk '{print $NF}' ~/.ssh/id_rsa.pub)/d' .ssh/authorized_keys; \
            cat tmp.pubkey >> .ssh/authorized_keys ; \
            rm tmp.pubkey)"
}
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
#
#    Do a ssh call
#    \params $1 user at host
#    \params $@:2 command to run
#    Example
#        ssh_call "a@webis16" "ls"
#
ssh_call() {
    host="$1"
    shift
    cmd="$@"
    ssh "$host" -o UserKnownHostsFile=/dev/null \
        -o StrictHostKeyChecking=no \
        -o LogLevel=error \
        -t -t "$cmd" 2> /dev/null
}
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

#
#    Check that host is alive.
#
#    \params $1 hostname
#    \return true if host is alive, false otherwhise.
#    Example call:
#        host_alive "mypc"
#
host_alive() {
    host="$1"

    if ping -c 1 "$host" &> /dev/null; then
        echo "true"
    else
        echo "false"
    fi
}

#    Check that network interface is valid.
#
#    \params $1 interface name
#    \return true if interface is available, false otherwhise.
#    Example call:
#        network_interface_available "eth0"
#
network_interface_available() {
    found=$(grep "$1" /proc/net/dev)

    if  [ -n "$found" ] ; then
        echo "true"
    else
        echo "false"
    fi
}

#
#    Create a temporary file.
#    Filename will be printed on stdout.
#
#    Note: Ubuntu12.04 has an own tempfile function,
#    but this is not general in all linux distributions.
tempfile() {
    filename=$(date +%s | sha256sum | base64 | head -c 32 ; echo)
    echo "/tmp/$filename"
}

#
#    Get a random free tcp port
#
#    \return random free port number on stdout
#    Example:
#        get_random_port
#
get_random_port() {
    python - <<END
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
print(s.getsockname()[1])
s.close()
END
}

#
#    Get owner of a file or directory
#
#    \params $@ file/dir
#    \return on stdout
#    Example:
#        get_owner "/home/"
#
get_owner() {
    stat -c %U "$@"
}

#
#    Get owner of a file or directory
#
#    \params $@ file/dir
#    \return on stdout
#    Example:
#        get_group "/home/"
#
get_group() {
    stat -c %G "$@"
}

259 260 261 262 263 264 265 266 267

#
#    Check if a variable is set
#
#    \params $@ NAME
#    \return (exit code)
#    Example:
#        is_var_set FOO && echo "yay! FOO is set!"
is_var_set() {
268
    [ ! -z "${!1+x}" ]
269 270
}

271 272 273 274 275 276 277

#   Check if the git repository in CWD
#   has unpulled commits on any remote
#   branch, without actually fetching
#   anything.
#
git_repo_has_updates() {
278
   git fetch --dry-run --verbose 2>&1 | grep -q 'git-upload-pack\|->'
279 280 281
}


282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
#
#    Printout settings and check configuration.
#
main() {
    if [[ -z "$_BASHHELPER"  ]]; then
        _BASHHELPER="included"
        export _BASHHELPER
    fi
}

usage() {
    echo "helper module"
}

#
#    Call main with arguments.
#
main "$@"