#!/bin/bash

set -e

ARGS=$@

while (( "$#" )); do
    if [ "$1" == "--garden-contour" ]; then
        contour=$2
        break
    fi
    shift
done

if [ -z "${contour}" ]; then
    echo "Garden contour name is required";
    exit 1;
fi

ya make -r ../../garden_oauth

export YAV_OAUTH_TOKEN=`yav oauth`
export GARDEN_OAUTH_TOKEN=`../../garden_oauth/garden_oauth`

ya package ./pkg.json

IMAGE=core-nmaps-export-cli:${contour}

cleanup ()
{
    CODE=$?
    rm ./core-nmaps-export-cli.dev.tar.gz

    read -p 'Keep container? [y/N] ' input
    if [[ $input =~ ^[Yy]$ ]]; then
        exit ${CODE}
    fi

    docker container rm ${contour}
    docker image rm ${IMAGE}
    exit ${CODE}
}

trap cleanup EXIT
docker build --network host -t core-nmaps-export-cli:${contour} - < ./core-nmaps-export-cli.dev.tar.gz
docker run --env YAV_OAUTH_TOKEN --env GARDEN_OAUTH_TOKEN --name ${contour} -it --network host ${IMAGE} ${ARGS}
