#!/bin/bash

set -vxeuo pipefail

export docker_image="nsls2/linux-anvil-cos7-x86_64:latest"
export env_name="2022-2.2-py38"
export conda_env_file="env-py38.yml"
export conda_binary="mamba"
export python_version="3.8"
export pkg_name=""
export pkg_version=""
export extra_packages="tmate mamba"
export channels="-c conda-forge"
export extra_cmd_before_install="yum install mesa-libGL -y"
export extra_cmd_after_install="conda remove perl --force -y"
export docker_upload="['ghcr', 'dockerhub']"
export zenodo_upload="no"
export docker_binary="docker"
export config_file="configs/config-py38.yml"
export script_name="runner-2022-2.2-py38.sh"

if [ -f "${env_name}.tar.gz" ]; then
    echo -e "File ${env_name}.tar.gz exists. Move it or remove it before proceeding."
    exit 1
fi

export build_dir="/build"
repo_dir="/repo"
artifacts_dir="${PWD}/artifacts"
mkdir -m 0777 -v -p ${artifacts_dir}

timestamp=$(date +%Y%m%d%H%M%S)

${docker_binary} image build . -t ${env_name}:latest \
                     -t ${env_name}:${timestamp}

daemon_mode="${GITHUB_ACTIONS:-false}"
if [ "${daemon_mode}" == "true" ]; then
    interactive="-d"
else
    interactive="-it"
fi
docker_run_cmd="${docker_binary} run ${interactive} --rm --name ${env_name} \
                    -v ${artifacts_dir}:${build_dir}:rw,z,delegated \
                    -v ${PWD}:${repo_dir} \
                    -e env_name -e channels -e build_dir \
                    ${env_name}:${timestamp} bash ${repo_dir}/export.sh"
echo -e "docker run command:\n\n${docker_run_cmd}\n"

if [ "${daemon_mode}" == "true" ]; then
    container_id=$(${docker_run_cmd})
    ${docker_binary} logs --follow $container_id
else
    ${docker_run_cmd}
fi

# echo $GITHUB_TOKEN | ${docker_binary} login ghcr.io --username $GITHUB_USERNAME --password-stdin
# ${docker_binary} tag ${env_name}:${timestamp} ghcr.io/$GITHUB_USERNAME/${env_name}:${timestamp}
# ${docker_binary} tag ${env_name}:${timestamp} ghcr.io/$GITHUB_USERNAME/${env_name}:latest
# ${docker_binary} image push ghcr.io/$GITHUB_USERNAME/${env_name}:${timestamp}
# ${docker_binary} image push ghcr.io/$GITHUB_USERNAME/${env_name}:latest


# echo $DOCKER_PASSWORD | ${docker_binary} login --username $DOCKER_USERNAME --password-stdin
# ${docker_binary} tag ${env_name}:${timestamp} $DOCKER_REPO:${timestamp}
# ${docker_binary} tag ${env_name}:${timestamp} $DOCKER_REPO:latest
# ${docker_binary} push $DOCKER_REPO:${timestamp}
# ${docker_binary} push $DOCKER_REPO:latest
