#! /bin/bash

set -e

img=registry-app.inhome.blapointe.com:5001/bel/ana-ledger:${1:-$(date +%Y%m%d%H%M)}
cd "$(dirname "$(dirname "$(realpath "$BASH_SOURCE")")")"
was=$(docker inspect $img | jq -r .[0].Id | sed 's/^sha256://')
docker build -f ./build/Dockerfile -t $img .
now=$(docker inspect $img | jq -r .[0].Id | sed 's/^sha256://')
docker push $img
if [ -n "$was" ] && [ "$was" != "$now" ] && docker inspect "$was" &> /dev/null; then
   docker rmi "$was" || true
   docker rmi $(docker ps | grep ${img%:*} | grep '<none>' | awk '{print $3}') || true
fi
