#!/bin/bash

set -e

OS="$(uname -s)"                        # supported: "Linux", "Darwin" (Mac)
ARCH="$(uname -m)"                      # supported: "x86_64", "aarch64" (ARM, Jetson Orin), "arm64" (ARM, Mac)

# check if user is in docker group
if [[ $OS != "Darwin" ]]; then
  if ! groups | grep -q "\bdocker\b"; then
    echo "User '${USER}' must be in 'docker' group to run containers."
    echo "User can be added via: sudo usermod -aG docker ${USER}"
    echo "Afterwards, the user may need to logout and login again."
  fi
fi

# check operating system and architecture
if ! { [[ $OS = "Linux" && $ARCH = "x86_64" ]] || [[ $OS = "Darwin" && $ARCH = "arm64" ]] || [[ $OS = "Linux" && $ARCH = "aarch64" ]]; }; then
  >&2 echo "docker-run does not support $OS with $ARCH architecture."
  exit 1
fi

# generate docker run/exec command
CMD_FILE=$(mktemp)
python3 -m docker_run "${@}" 2>&1 >$CMD_FILE
CMD=$(cat $CMD_FILE)
rm $CMD_FILE

# convert command string to array to allow for escaped characters, e.g. "docker run -v /path\ with\ spaces:/path\ with\ spaces ..."
CMD_ARRAY=()
  while IFS= read -r -d ' ' part; do
    while [[ $part == *"\\" ]]; do
      part+=" "
      part="${part//\\/}"
      IFS= read -r -d ' ' next_part
      part+=$next_part
    done
    CMD_ARRAY+=("$part")
  done <<< "$CMD"
  CMD_ARRAY+=("${part%$'\n'}")

# execute command
if [[ ! -z "$CMD" ]]; then
  echo -e "================================================================================\n"
  exec "${CMD_ARRAY[@]}"
fi
