#!/usr/bin/env bash
# Mock docker for tools/test-tools.sh: a container is a directory, an image is a
# copy of one, so `run` from a committed image really is copy-on-write. Implements
# only what tools/mutation-table.sh and tools/cargo-mutants.sh --host call: run, commit,
# cp, rm, rmi. The in-container paths /mt, /cm, /out and /seed map to the mounted host
# directories (/out is written through), and the script's own /src and /tmp/mtm live
# inside the container directory.
FD=${FAKE_DOCKER:?}; mkdir -p "$FD/c" "$FD/i"
imgdir() { echo "$FD/i/${1//[:\/]/_}"; }
cmd=$1; shift
case $cmd in
  run)
    rm_after=0; name=''; mt=''; cm=''; out=''; seed=/nonexistent; labels=0; envs=()
    while [ $# -gt 0 ]; do
      case $1 in
        --rm) rm_after=1 ;;
        --name) name=$2; shift ;;
        --label) labels=$((labels + 1)); shift ;;
        -v) case $2 in *:/mt:ro) mt=${2%:/mt:ro} ;; *:/cm:ro) cm=${2%:/cm:ro} ;; *:/out) out=${2%:/out} ;; *:/seed:ro) seed=${2%:/seed:ro} ;; esac; shift ;;
        -e) case $2 in BASH_ENV=*) ;; *) envs+=("$2") ;; esac; shift ;;
        -w) shift ;;
        --*=*) ;;
        -*) echo "fake docker: unknown flag $1" >&2; exit 125 ;;
        *) break ;;
      esac
      shift
    done
    image=$1; shift
    [ "$labels" -ge 1 ] || { echo "fake docker: container without the job label" >&2; exit 125; }
    c=$FD/c/$name; rm -rf "$c"
    if [ -d "$(imgdir "$image")" ]; then cp -a "$(imgdir "$image")" "$c"; else mkdir -p "$c"; fi
    echo "run $name $image" >>"$FD/log"
    script=${*: -1}; script=${script//\/mt\//$mt/}; script=${script//\/cm\//$cm/}
    ( for e in "${envs[@]}"; do export "$e"; done
      export MT_SRC=$c/src MT_M=$c/tmp/mtm MT_DIR=$mt MT_SEED=$seed CM_SRC=$c/src CM_DIR=$cm CM_OUT=$out CM_SEED=$seed CM_TMP=$c/tmp
      bash -o pipefail -c "$script" )
    rc=$?
    [ "$rm_after" = 0 ] || rm -rf "$c"
    exit $rc ;;
  commit) rm -rf "$(imgdir "$2")"; cp -a "$FD/c/$1" "$(imgdir "$2")"; echo "commit $1 $2" >>"$FD/log" ;;
  cp) f=$FD/c/${1%%:*}${1#*:}; tar -C "$(dirname "$f")" -c "$(basename "$f")" ;;
  rm) shift; for n in "$@"; do case $n in -*) ;; *) rm -rf "$FD/c/$n" ;; esac; done ;;
  rmi) shift; for n in "$@"; do case $n in -*) ;; *) rm -rf "$(imgdir "$n")" ;; esac; done ;;
  *) echo "fake docker: unsupported $cmd" >&2; exit 125 ;;
esac
