diff options
Diffstat (limited to 'misc/launch')
-rwxr-xr-x | misc/launch | 110 |
1 files changed, 110 insertions, 0 deletions
diff --git a/misc/launch b/misc/launch new file mode 100755 index 0000000..5947ae7 --- /dev/null +++ b/misc/launch @@ -0,0 +1,110 @@ +#!/bin/sh +awk=awk +me() { basename "$0"; } + +printhelp() { +cat << HELPDOC +Usage: + $(me): [-gh] [COMMAND] [COMMAND ARGS]... + +Args: + -g, --gen-cache : Force generate cache + -h, --help : show this help message + +Config Syntax: + +host [HOSTNAME] + Add a new host. Hosts can be referenced using their number starting with 1. + [COMMAND] + launch [COMMAND] will start the process specified for the specific hostname. Aliases are separated by |. + [TAB][SHELL] + Run this shell command when the above [COMMAND] is specified. In order of hostnames. Can be a number to reference to a hostname, a '-' to disregard this command for the specific host, or a '^' to reference the previous command. +HELPDOC +} + +# Make sure user is using GNU Awk (gawk) +checkawk() { + if ! ($awk -V >/dev/null 2>/dev/null && $awk -V | grep "GNU Awk" >/dev/null); then + if command -v gawk > /dev/null; then + awk=gawk + else + echo "$(me) requires GNU Awk (gawk) to function properly. Please install GNU Awk and try again." + exit 0 + fi + fi +} + +gencache() { +$awk ' +BEGIN { + print "run=\"$1\"; shift" + print "case \"$run\" in" +} +{ + sub(/#.*/, "") # Remove comments + if (!/^\s*$/) { + if (/^\+host/) { + sub(/\s*\+host\s*/, "") + h++ + hosts[h] = $0 + } + else { + if (!/^\t/) { + hostnum = 1 + o++ + opts[o] = $0 + } + else { + sub(/^\t/, "") + if ($0 == "^") + $0 = cache + else if ($0 ~ /^[0-9]*$/) + $0 = cmds[hosts[$0]":"opts[o]] + cmds[hosts[hostnum]":"opts[o]] = cache = $0 + hostnum++ + } + } + } +} +END { + for (host in hosts) { + if (hosts[host] != "'`hostname`'") + continue + for (cmd in cmds) { + if (cmd ~ hosts[host] && cmds[cmd] && cmds[cmd] != "-") { + i = cmd + sub(/.*:/, "", cmd) + print "\t"cmd") "cmds[i]" \"$@\" & ;;" + } + } + } + print "\t*) command -v \"$run\" >/dev/null && exec \"$run\" \"$@\" || echo \"\\`$run${@:+ $@}\\` Does not exist or exited with an error\" ;;" + print "esac" +} +' $conf > $cache +chmod +x $cache +} + +# Config file setup +confdir=${XDG_CONFIG_HOME:-~/.config}/launch +conf=$confdir/config +if [ ! -e $conf ]; then + mkdir -p $confdir + echo "#HOSTS\n+host $(hostname)\n\n#OPTS\ntest\n\techo \"Tested!\"" > $conf + echo "No config file exists! new config file created at $conf! Exiting\n" + printhelp + exit 1 +fi + +# Cache file setup +cachedir=${XDG_CACHE_HOME:-~/.cache}/launch +cache=$cachedir/cache +[ ! -e $cache ] && mkdir -p $cachedir && gencache +[ $conf -nt $cache ] && gencache + +# Command line options +checkawk +case "$1" in + -g|--gen-cache) echo "Generating new cache: $cache"; gencache && cat $cache ;; + -h|--help|'') printhelp ;; + *) exec $cache "$@" ;; # Run +esac |