#!/bin/sh
set -eu

release_dir=${UNIDESK_HOST_RELEASE_DIR:-/workspace/release}
source_dir=${UNIDESK_HOST_SOURCE_DIR:-/workspace/source}
digest_file=${UNIDESK_HOST_DIGEST_FILE:-/workspace/image-digest-ref}
metadata_file=${UNIDESK_HOST_BUILD_METADATA_FILE:-/workspace/build-metadata.json}
build_log=${UNIDESK_HOST_BUILD_LOG:-/workspace/image-build.log}
source_commit=${SOURCE_COMMIT:?SOURCE_COMMIT is required}

action=$(cat "$release_dir/action")
reason=$(cat "$release_dir/reason")
if [ "$action" != build ]; then
  : >"$digest_file"
  : >"$metadata_file"
  printf '{"ok":true,"phase":"image-build","status":"skipped","action":"%s","reason":"%s","sourceCommit":"%s","valuesPrinted":false}\n' "$action" "$reason" "$source_commit"
  exit 0
fi

image_repository=$(cat "$release_dir/image-repository")
dockerfile=$(cat "$release_dir/dockerfile")
network_mode=$(cat "$release_dir/network-mode")
http_proxy=$(cat "$release_dir/http-proxy")
https_proxy=$(cat "$release_dir/https-proxy")
all_proxy=$(cat "$release_dir/all-proxy")
no_proxy=$(cat "$release_dir/no-proxy")
image_ref="$image_repository:$(printf '%s' "$source_commit" | cut -c1-12)"

rm -f "$metadata_file" "$build_log" "$digest_file"
env HTTP_PROXY="$http_proxy" HTTPS_PROXY="$https_proxy" ALL_PROXY="$all_proxy" NO_PROXY="$no_proxy" \
  http_proxy="$http_proxy" https_proxy="$https_proxy" all_proxy="$all_proxy" no_proxy="$no_proxy" \
  buildctl-daemonless.sh build \
    --allow network.host \
    --frontend dockerfile.v0 \
    --local context="$source_dir" \
    --local dockerfile="$source_dir" \
    --opt "filename=$dockerfile" \
    --opt "network=$network_mode" \
    --opt "build-arg:HTTP_PROXY=$http_proxy" \
    --opt "build-arg:HTTPS_PROXY=$https_proxy" \
    --opt "build-arg:ALL_PROXY=$all_proxy" \
    --opt "build-arg:NO_PROXY=$no_proxy" \
    --metadata-file "$metadata_file" \
    --output "type=image,name=$image_ref,push=true,registry.insecure=true" >"$build_log" 2>&1
cat "$build_log"
test -s "$metadata_file"
printf '%s\n' "$image_ref" >"$digest_file"
printf '{"ok":true,"phase":"image-build","status":"built","sourceCommit":"%s","imageRef":"%s","metadataReady":true,"valuesPrinted":false}\n' "$source_commit" "$image_ref"
