kylemanna
11/11/2014 - 9:14 AM

cargo

#!/bin/bash
#
# Cargo - an object that passes through a Docker container
#
# Author: Kyle Manna <kyle@kylemanna.com>
#

IMG=$1
SRC=$2
IMG_RX="::rxcargo::"
TAG_PAYLOAD="::payload::"

#
# When invoked inside the docker container (i.e. receiver)
#
if [ "$IMG" = "$IMG_RX" ]; then
    cargo_tmp=$(mktemp -d)
    echo "In unpack"
    match=$(grep --text --line-number "^$TAG_PAYLOAD\$" $0 | cut -d ':' -f 1)
    tail -n +$((match + 1)) $0 | tar -xvf - -C $cargo_tmp

    $cargo_tmp/run.sh

    read x x gw x < <(ip route list 0/0)
    echo ::gateway $gw

    exit $?
fi

#
# When invoked from the host (i.e. transmitter)
#
if [ -z "$IMG" -o -z "$SRC" ]; then
    echo "Invalid arguments"
    echo
    echo "usage: $0 DOCKER_IMAGE CARGO_SRC_DIRECTORY"
    echo
    exit 1
fi

mkdir .cargo
mkfifo .cargo/fifo

#set -x
#( cat $0 ; echo exit 0 ; tar cf - . -C $SRC ) | docker run --rm -i $IMG bash /dev/stdin $IMG_RX
( cat $0 ; echo "$TAG_PAYLOAD" ; tar -cf - -C $SRC --exclude ./.git . ) \
    | docker run -v --rm -i $IMG bash -c "cat > /tmp/cargo.sh && bash /tmp/cargo.sh \"$IMG_RX\""

jobs -p | xargs kill
wait

# Never go beyond this as it's binary tarball most likely
exit 0