#!/usr/bin/env bash

set -o errexit
set -o pipefail

nfs_setup() {
  # Adapted from https://medium.com/@sean.handley/how-to-set-up-docker-for-mac-with-native-nfs-145151458adc
  # Further adapted from https://github.com/drud/ddev/blob/master/scripts/macos_ddev_nfs_setup.sh

  # Updated from DDEV's version to remove DDEV-local references.

  OS=$(uname -s)

  if [ $OS != "Darwin" ]; then
    echo "This script is OSX-only. Please do not run it on any other Unix."
    exit 101
  fi

  # Share /Users folder. If the projects are elsewhere the /etc/exports will need
  # to be adapted.
  # If Catalina or later, the share directory has to be /System/Volumes/Data/...
  SHAREDIR=${HOME}
  if [ -d /System/Volumes/Data${HOME} ] ; then
      SHAREDIR=/System/Volumes/Data${HOME}
  fi

  if [[ $EUID -eq 0 ]]; then
    echo "This script must NOT be run with sudo/root. Please re-run without sudo." 1>&2
    exit 102
  fi

  # nfsd on mac can be enabled but will only run if /etc/exports is present. If it's already configured for this
  # version of MacOS, we early return assuming nfs setup has already been performed.
  FILE=/etc/exports
  grep -q -- "^${SHAREDIR}.*localhost\$" "$FILE" && return

  echo "
  +-------------------------------------------+
  | It appears you have not yet set up NFS.   |
  | Setup native NFS on macOS for Docker      |
  | Only localhost is allowed access;         |
  | Your home directory is shared by default. |
  | But, of course, pay attention to security.|
  +-------------------------------------------+
  "

  docker version > /dev/null 2>&1 || ( echo "Docker does not seem to be running or functional, is it installed?" && exit 103)

  open -a Docker

  while ! docker ps > /dev/null 2>&1 ; do sleep 2; done

  RUNNING=$(docker ps -q)
  if [[ ! -z "$RUNNING" ]]; then
      echo "== Stopping running docker containers..."
      docker stop "$RUNNING"
  fi
  echo "== Pruning volumes..."
  docker volume prune -f > /dev/null

  echo
  osascript -e 'quit app "Docker"'

  echo "== Setting up nfs, includes your home directory... password required to edit $FILE and start nfsd..."

  sudo bash -c "echo >> $FILE" || ( echo "Unable to edit /etc/exports, need Full Disk Access on Mojave and later" && exit 103 )
  sudo echo "${SHAREDIR} -alldirs -mapall=$(id -u):$(id -g) localhost" | sudo tee -a $FILE > /dev/null

  LINE="nfs.server.mount.require_resv_port = 0"
  FILE=/etc/nfs.conf
  grep -qF -- "$LINE" "$FILE" || ( sudo echo "$LINE" | sudo tee -a $FILE > /dev/null )

  echo "== Restarting nfsd..."
  sudo nfsd enable && sudo nfsd restart
  open -a Docker
}

# Detect broken recursion.
if [ "$1" == "version" ]; then
  if [ ! -z "$FRU_DEV_SHIM_RECURSION" ]; then exit 99; fi
  exec "$DOCKER_COMPOSE" "$@"
fi

# Use the next occurrence of docker-compose in the path.
DOCKER_COMPOSE=$(which -a docker-compose | sed -n '2p')

FRU_DEV_SHIM_RECURSION=1 eval "$DOCKER_COMPOSE version" > /dev/null 2>&1 || ( echo "Cannot find docker-compose; is it installed?" && exit 103)

nfs_setup

if [ -z "$DOCKER_COMPOSE" ]; then
  echo "Could not find docker-compose."
  exit 100
fi

while getopts ":f:" o; do
    case "${o}" in
        f)
            CLI_F_ARG=${OPTARG}
            ;;
    esac
done

if [ ! -z "$CLI_F_ARG" ] || [ ! -z "$COMPOSE_FILE" ]; then
  echo "Shim not running as docker-compose file is specified by flag or environment variable."
  exec "$DOCKER_COMPOSE" "$@"
fi

set +e
# This will be in the path.
COMPOSE_FILE=$(fru-mac-environment-transform)
EXITCODE=$?
if [ $EXITCODE -eq 0 ]; then exec "env" "COMPOSE_FILE=$COMPOSE_FILE" "$DOCKER_COMPOSE" "$@"; else echo "$COMPOSE_FILE" && exit $EXITCODE; fi
