#!/bin/sh

set -eu


basedir="$(readlink -f "$(dirname $0)")"
tmpdir="$basedir"/tmp
datadir="$tmpdir"/data
mkdir -p "$datadir"

dockerfile="$datadir"/../Dockerfile.dev
(
  sed -e '1,/WORKDIR/!d' "$basedir"/Dockerfile
  echo 'RUN apt-get install -q2 snakefood flake8 git python3-wheel chromium nodejs && \'
  echo "    groupadd -g $(id -g) $(id -gn) && \\"
  echo "    useradd -m -u $(id -u) -g $(id -g) -s /bin/bash ${USER}"
  echo "USER ${USER}"
  echo 'CMD sh -c "./manage.py test && ./manage.py migrate && ./manage.py runserver 0.0.0.0:8000"'
) > "$dockerfile"

docker build -t squad/dev -f "$dockerfile" .

extra_volumes=''
for v in $HOME/.gitconfig $HOME/.config/git; do
  if [ -e "$v" ]; then
    extra_volumes="$extra_volumes --volume=$v:$v"
  fi
done

exec docker run \
  --env=XDG_DATA_HOME=/app/tmp/data \
  --publish=8000:8000 \
  --volume="$basedir":/app \
  $extra_volumes \
  --rm \
  -it squad/dev "$@"
