#!/usr/bin/env bash

IMG_NAME_PREFIX=git.teltonika.lt:4567/docker/buildsys/
IMG_NAME=${IMG_NAME:-${IMG_NAME_PREFIX}tools}
IMG_TAG=${IMG_TAG:-1.10}

# Color codes
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

err() {
	echo -e "${RED}==> $1$NC"
}

info() {
	echo -e "${YELLOW}==> $1$NC"
}

calc_images_size() {
	for id in $(docker image ls --all --format '{{.ID}}' 'git.teltonika.lt:4567/docker/buildsys/*'); do
		docker history "$id" --format '{{.Size}} {{.CreatedBy}}'
	done | sort -u | cut -d' ' -f1 | tr . , | sed -E 's|([0-9]+(,[0-9]+)?[kKMG]?)B|\1|g' | numfmt --from=iec | awk 'BEGIN { sum = 0 } { sum += $1 } END { print sum	}'
}

cleanup() {
	local obsolete_containers
	obsolete_containers=$($DOCKER_CMD ps --all | grep '/buildsys/tool.*"tail -f /toolchain' | awk '{print $1}')
	[[ -n $obsolete_containers ]] && {
		#shellcheck disable=SC2086
		$DOCKER_CMD stop $obsolete_containers &>/dev/null
		obsolete_containers=$($DOCKER_CMD ps --all | grep '/buildsys/tool.*"tail -f /toolchain' | awk '{print $1}')
		[[ -n $obsolete_containers ]] && {
			#shellcheck disable=SC2086
			$DOCKER_CMD rm $obsolete_containers &>/dev/null
		}
	}

	local size
	size=$(calc_images_size)
	[[ $size -lt 10737418240 ]] && return

	#shellcheck disable=SC2016
	info "$(printf 'Toolchain docker images take up %s on disk. You can cleanup all of them with:\n\n\t$ %s image rm $(%s image ls --all --format "{{.ID}}" "*/docker/buildsys/*")\n\n' "$(echo "$size" | numfmt --to=iec)" "$DOCKER_CMD" "$DOCKER_CMD")"
}

# Check for Docker installation
if ! command -v docker &>/dev/null; then
	err "Docker could not be found."
	exit 1
fi

# Chicken and egg problem - cannot reliably check if docker is running before determining correct permissions,
# but permissions check might print wrong information if the docker is not running.

# Permission handling for Docker command
DOCKER_CMD="docker"
if $DOCKER_CMD info -f "{{println .SecurityOptions}}" 2>/dev/null | grep -q rootless; then
	info "Cannot use rootless docker due to file ownership issues. Will proceed with sudo..."
	DOCKER_CMD="sudo docker"
fi
if ! $DOCKER_CMD ps &>/dev/null; then
	info "Docker commands require sudo. Attempting to proceed with sudo..."
	DOCKER_CMD="sudo docker"
fi

# Check if Docker daemon is running
if ! $DOCKER_CMD info &>/dev/null; then
	info "Docker is not running."
	# Check for systemd to start Docker
	if ! command -v systemctl &>/dev/null; then
		err "Systemd not found. Please start Docker manually."
		exit 1
	fi

	info "Attempting to start Docker using systemd..."
	sudo systemctl start docker || {
		err "Failed to start Docker. Please start Docker manually."
		exit 1
	}
	info "Docker started successfully."
fi

# Check if the Docker image and tag exists locally
if ! $DOCKER_CMD image inspect "$IMG_NAME:$IMG_TAG" >/dev/null 2>&1; then
	info "Docker image $IMG_NAME:$IMG_TAG not found locally. Attempting to download..."
	$DOCKER_CMD login "${IMG_NAME%%/*}" -u oauth2 -p aCb3RawxFnwuSZymE7XM 2>/dev/null # a shared token for read-only access to the container registry
	$DOCKER_CMD pull "$IMG_NAME:$IMG_TAG" || {
		err "Failed to download Docker image. Please check the image name and tag."
		exit 1
	}
fi

WORKDIR="$(pwd)"
PASSWD="/etc/passwd"
GROUP="/etc/group"
HOSTS="/etc/hosts"
USER_GROUP="$(id -u "$USER"):$(id -g "$USER")"

CONTAINER_NAME=${IMG_NAME##"$IMG_NAME_PREFIX"}_${WORKDIR}_${IMG_TAG}
CONTAINER_NAME=${CONTAINER_NAME//\//_}
CONTAINER_NAME=${CONTAINER_NAME//__/_}
CONTAINER_NAME=${CONTAINER_NAME//./_}

# Execute Docker run command with dynamic image name and tag

if $DOCKER_CMD ps --all --quiet --filter name="$CONTAINER_NAME" --filter status=exited | grep -q .; then
	$DOCKER_CMD rm "$CONTAINER_NAME"
fi

gen_dns() {
	local default_routes
	default_routes=$(ip route | grep default)

	while read -r ip; do
		echo "$default_routes" | grep -q " $ip " && continue # skip gateway DNS to avoid DNS resolution issues when using VPNs
		printf -- '--dns %s ' "$ip"
	done < <(grep -oP '(?<=nameserver\s)(\d{1,3})(\.(?1))+' /etc/resolv.conf)
}

# Start a long-running container
if ! $DOCKER_CMD ps --all --quiet --filter name="$CONTAINER_NAME" | grep -q .; then
	VOLUME_PREFIX="${WORKDIR//\//_}"
	VOLUME_STAGING_HOST="${VOLUME_PREFIX:1}_staging_host"
	VOLUME_STAGING_HOSTPKG="${VOLUME_PREFIX:1}_staging_hostpkg"
	create_volume "$VOLUME_STAGING_HOST"
	create_volume "$VOLUME_STAGING_HOSTPKG"

	#shellcheck disable=SC2046
	$DOCKER_CMD run -d \
		--rm \
		--name "$CONTAINER_NAME" \
		--user "$USER_GROUP" \
		$(gen_dns) \
		--workdir "$WORKDIR" \
		--volume "$HOME:$HOME" \
		--volume "$WORKDIR:$WORKDIR" \
		--volume "$PASSWD:$PASSWD:ro" \
		--volume "$GROUP:$GROUP:ro" \
		--volume "$HOSTS:$HOSTS:ro" \
		--env EXEC_REAL_BUILD=1 \
		--env INSIDE_DOCKER=1 \
		--ulimit "nofile=1024:1048576" \
		"$IMG_NAME:$IMG_TAG" \
		tail -f /toolchain/host/.prepared >/dev/null
fi

$DOCKER_CMD exec -it "$CONTAINER_NAME" "$@"
