#!/bin/bash -le
# purpose: Create package and place it in /dock
# requires: /gridded_glm to be mounted with package contents (gridded_glm in repository)
# note: The shebang at the top of this file is needed as-is. The '-l' will
#       load the .bashrc which allows us to use conda. The '-e' triggers exit
#       on error behavior. We cannot use '/usr/bin/env bash -le' since most
#       linux versions only parse the first two arguments of a shebang.

if [ $# -eq 1 ]; then
    version=$1
    lmatools_ref=minvaluegrids
    glmtools_ref=ugf-newgrid
elif [ $# -eq 3 ]; then
    version=$1
    lmatools_ref=minvaluegrids
    glmtools_ref=ugf-newgrid
else
    echo "Usage: package.sh vX.Y.Z [lmatools_ref glmtools_ref]"
    exit 1
fi

conda activate build

# Debug Info
which python
conda info -a
conda list --export
echo "Version specified: ${version}"
echo "lmatools reference: ${lmatools_ref}"
echo "glmtools reference: ${glmtools_ref}"

# Turn on command printing here because we don't need all of the `conda`
# internal bash commands to pollute our output
set -x

# Install glmtools and related packages
# All dependencies should have been built with the buildbucket
# Careful: Could result in missing dependencies but we want reproducibility
pip install --no-deps git+https://github.com/deeplycloudy/lmatools.git@${lmatools_ref}
pip install --no-deps git+https://github.com/deeplycloudy/stormdrain.git
pip install --no-deps git+https://github.com/deeplycloudy/glmtools.git@${glmtools_ref}

# Build a tarball version of the current conda environment
conda_tb=conda_lmatools-${lmatools_ref}_glmtools-${glmtools_ref}.tar.gz
conda pack -n build -o ${conda_tb}

# Build up our package directory
pkg_name=cspp_geo_gridded_glm-${version}
mkdir -p ${pkg_name}
cd ${pkg_name}
mkdir -p bin opt/conda
# Copy package scripts/data to package directory
cp /gridded_glm/PACKAGE_README.md ./README.md
cp /gridded_glm/bin/* ./bin/
# Untar the tarball so we can put things where we want
tar -xz -C ./opt/conda -f ../${conda_tb}
# Go back to original work directory
cd ..

# Create tarball of package directory
tar -czf ${pkg_name}.tar.gz ${pkg_name}
mv ${pkg_name}.tar.gz /dock/

