#!/bin/bash

# convert a Brew-friendly Dockerfile into one we can run locally

# Sample usage:
# ~/bin/makeLocalDockerfile.sh -t pr.loc -f ./Dockerfile
# ~/bin/makeLocalDockerfile.sh -t dr.loc -f ./Dockerfile

# read commandline args
while [[ "$#" -gt 0 ]]; do
  case $1 in
    '-f') DOCKERFILE="$2"; shift 1;;
    '-t') tag="$2"; shift 1;;
       *) others="$others $1"; shift 0;;
  esac
  shift 1
done

if [[ ! ${DOCKERFILE} ]]; then
	for d in build/dockerfiles docker .; do
		for f in rhel.Dockerfile Dockerfile; do
			if [[ -f ${d}/${f} ]]; then
				DOCKERFILE=${d}/${f}
				break 2;
			fi
		done
	done
	# echo "Using ${DOCKERFILE} ... "
fi

if [[ ! ${tag} ]]; then
	image=$(pwd); image=${image##*/}; image=$(echo $image | tr "A-Z" "a-z"); # echo $image
	tag="${image}:local"
fi

DOCKERFILELOCAL=${DOCKERFILE%/*}/local.${DOCKERFILE##*/}

# 1. fix FROM
# 2. apply .repo file
cat ${DOCKERFILE} | sed \
	-e "s#FROM scratch#FROM ubi8-minimal#" \
	-e "s#^FROM #FROM registry.redhat.io/#" \
	-e "s#^FROM registry.redhat.io/registry.redhat.io/#FROM registry.redhat.io/#" \
	-e "s#^FROM registry.redhat.io/registry.access.redhat.com/#FROM registry.redhat.io/#" \
	-e "s#^FROM registry.redhat.io/registry-proxy.engineering.redhat.com/#FROM registry-proxy.engineering.redhat.com/#" \
	-e "s%# \(COPY .\+\.repo /etc/yum.repos.d/\)%\1%" \
	-e "s%# COPY content_sets%COPY content_sets%" > ${DOCKERFILELOCAL}

CMD="podman build . -f ${DOCKERFILELOCAL} -t $tag $others"
echo $CMD
$CMD
