#!/bin/bash
# Copyright (C) 2021 Associated Universities, Inc. Washington DC, USA.
#
# This file is part of NRAO Workspaces.
#
# Workspaces is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Workspaces is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Workspaces.  If not, see <https://www.gnu.org/licenses/>.
#

# Set failfast
set -e
set -o pipefail

BUILD_DIR=/builds/ssa/workspaces/pexes
[[ -d $BUILD_DIR ]] ||  mkdir -p $BUILD_DIR

cd  apps/cli/executables/pexable/
for pexable in "$@"
do
  if [ $pexable == "ingest" ]; then
    echo "Skipping $pexable"
    continue
  fi

  # if directory doesn't exist, skip
  if [ ! -d "$pexable" ]; then
    echo "Directory $pexable doesn't exist skipping"
    continue
  fi

  cd  "$pexable"
  if [ -e setup.py ]; then
    until python3.10 setup.py bdist_pex --bdist-all --bdist-dir="$BUILD_DIR" --pex-args="--python-shebang /home/ssa/bin/python3.10"; do
      echo "PEX build failed. Retrying."; sleep 2;
    done
  else
    echo "PEX build impossible in $PWD because there is no setup.py file"
  fi
  cd ..
done
