#!/bin/sh

# https://github.com/mkropat/sh-realpath
realpath() {
    canonicalize_path "$(resolve_symlinks "$1")"
}
resolve_symlinks() {
    _resolve_symlinks "$1"
}
_resolve_symlinks() {
    _assert_no_path_cycles "$@" || return

    local dir_context path
    path=$(readlink -- "$1")
    if [ $? -eq 0 ]; then
        dir_context=$(dirname -- "$1")
        _resolve_symlinks "$(_prepend_dir_context_if_necessary "$dir_context" "$path")" "$@"
    else
        printf '%s\n' "$1"
    fi
}
_prepend_dir_context_if_necessary() {
    if [ "$1" = . ]; then
        printf '%s\n' "$2"
    else
        _prepend_path_if_relative "$1" "$2"
    fi
}
_prepend_path_if_relative() {
    case "$2" in
        /* ) printf '%s\n' "$2" ;;
         * ) printf '%s\n' "$1/$2" ;;
    esac
}
_assert_no_path_cycles() {
    local target path

    target=$1
    shift

    for path in "$@"; do
        if [ "$path" = "$target" ]; then
            return 1
        fi
    done
}
canonicalize_path() {
    if [ -d "$1" ]; then
        _canonicalize_dir_path "$1"
    else
        _canonicalize_file_path "$1"
    fi
}
_canonicalize_dir_path() {
    (cd "$1" 2>/dev/null && pwd -P)
}
_canonicalize_file_path() {
    local dir file
    dir=$(dirname -- "$1")
    file=$(basename -- "$1")
    (cd "$dir" 2>/dev/null && printf '%s/%s\n' "$(pwd -P)" "$file")
}


CONTAINER_IMAGE="registry.makerforce.io/ambrose/env"
CONTAINER_IMAGE_PWN="registry.makerforce.io/ambrose/pwn"
CONTAINER_HOME="/home/ambrose"

OPTIND=1

workdir=""
delete=""
name=""
ports="\n\t"
volumes=""
image="$CONTAINER_IMAGE"

show_help() {
cat << EOF
Usage: ${0##*/} [-xwt] [-n NAME] [-p PORT]... [-v LIST]... [CMD]...
       ${0##*/} -l
       ${0##*/} -a NAME
       ${0##*/} -e NAME [CMD]...
       ${0##*/} -h
Starts an env Docker container. If CMD is specified, starts CMD 
instead of a shell.

   -x       delete Docker container after exit. will loose data
   -w       forward \$PWD into $CONTAINER_HOME/src, and start there
   -n NAME  give container a NAME
   -p PORT  forward host PORT to container PORT
   -h       use host networking instead
   -v LIST  mount volume LIST. specify as LOCAL:MOUNT
   -t       run pwntools instead
   -l       list running containers and exit
   -a NAME  attach to a running container
   -e NAME  execute zsh or CMD on a running container
   -h       display this help and exit

EOF
}

list_running() {
docker ps \
	--filter \
	label=org.label-schema.vcs-url=https://git.makerforce.io/ambrose/env.git \
	--format \
	"table {{.Names}}\t{{.RunningFor}}\t{{.Ports}}\t{{.Command}}"
}

while getopts "xwn:p:v:tla:e:h" opt; do
	case "$opt" in
	x)
		delete="--rm "
		;;
	w)
		workdir="\n\t--workdir $CONTAINER_HOME/src "
		volumes="$volumes\n\t-v '$(realpath $PWD)':$CONTAINER_HOME/src "
		;;
	n)
		name="--name $OPTARG "
		;;
	p)
		ports="$ports-p $OPTARG:$OPTARG "
		;;
	h)
		host="--net host "
		;;
	v)
		volumes="$volumes\n\t-v '$OPTARG' "
		;;
	t)
		image="$CONTAINER_IMAGE_PWN"
		;;
	l)
		list_running
		exit 0
		;;
	a)
		mode_attach="true"
		name="$OPTARG"
		;;
	e)
		mode_execute="true"
		name="$OPTARG"
		;;
	h)
		show_help
		exit 0
		;;
	:)
		echo "Option -$OPTARG requires an argument." >&2
		show_help
		exit 1
		;;
	\?)
		echo "Invalid option: -$OPTARG" >&2
		show_help
		exit 1
		;;
	esac
done

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

if [ "$ports" = "\n\t" ]; then
	ports=""
fi

if [ "$mode_attach" = "true" ]; then
	docker attach \
		$name
	exit 0
fi

if [ "$mode_execute" = "true" ]; then
	cmd="$@"
	if [ -z "$@" ]; then
		cmd="/bin/zsh"
	fi
	docker exec -it \
		$name \
		$cmd
	exit 0
fi

docker pull $image

cmd="\n\
docker run -it $delete$name$ports$host$workdir$volumes\n\
	$image \n\
	$@\
"

echo
echo "Running: $cmd"

bash -c "`echo $cmd | tr -d '\n'`" # Ugh...
