#!/bin/sh

set -e
set -u

PROJECT_NAME=crystal-builder
WORKDIR="/$PROJECT_NAME"

CDATE="$(date --rfc-3339=seconds |head -c19 |sed -e 's/[-:]//g' -e 's/ /-/')"
CNAME=""
CID=""

crun() {
	name="$1"
	base="$2"
	CNAME="$name-$CDATE"
	CID="$(docker run -it \
		--rm \
		--name "$CNAME" \
		--detach \
		-v "./:$WORKDIR" \
		-w "$WORKDIR" \
		"$base" \
		sleep infinity)"
	if [ -z "$CID" ]; then
   	   	>&2 echo "ERROR: Unable to run $name container ($CNAME)"
   	   exit 1
	fi

}

cclean() {
	>&2 printf "INFO: Cleaning containers... "
	docker kill "$CID" > /dev/null
	echo "done"
}
trap "cclean" EXIT


## 0. Run base image

## 1. Install the latest crystal release
## Ref. https://crystal-lang.org/install/
crun step1 debian:12
docker exec -it "$CID" sh "$WORKDIR/setup/step1.sh"
docker commit "$CID" "$PROJECT_NAME:step1"
cclean

## 2. Make sure a supported LLVM version is present in the path
## (When possible, use the latest supported version)
crun step1 "$PROJECT_NAME:step1"
cclean

## 3. Make sure to install all the required libraries. You might also want to read the contributing guide.

## 4. Clone the repository: git clone https://github.com/crystal-lang/crystal

## 5. Run make to build your own version of the compiler.

## 6. Run make std_spec compiler_spec to ensure all specs pass, and you’ve installed everything correctly.

## 7. Use bin/crystal to run your crystal files.