1#!/usr/bin/env bash
2# Copyright (c) the JPEG XL Project Authors. All rights reserved.
3#
4# Use of this source code is governed by a BSD-style
5# license that can be found in the LICENSE file.
6
7set -eu
8
9MYDIR=$(dirname $(realpath "$0"))
10
11declare -a TARGETS
12
13load_targets() {
14  # Built-in OSX "find" does not support "-m".
15  FIND=$(which "gfind" || which "find")
16  for f in $(${FIND} -maxdepth 1 -name 'Dockerfile.*' | sort); do
17    local target="${f#*Dockerfile.}"
18    TARGETS+=("${target}")
19  done
20}
21
22usage() {
23    cat >&2 <<EOF
24Use: $1 [targets]
25
26Available targets:
27  * all
28EOF
29  for target in "${TARGETS[@]}"; do
30    echo "  * ${target}" >&2
31  done
32}
33
34build_target() {
35  local target="$1"
36
37  local dockerfile="${MYDIR}/Dockerfile.${target}"
38  # JPEG XL builder images are stored in the gcr.io/jpegxl project.
39  local tag="gcr.io/jpegxl/${target}"
40
41  echo "Building ${target}"
42  if ! sudo docker build --no-cache -t "${tag}" -f "${dockerfile}" "${MYDIR}" \
43      >"${target}.log" 2>&1; then
44    echo "${target} failed. See ${target}.log" >&2
45  else
46    echo "Done, to upload image run:" >&2
47    echo "  sudo docker push ${tag}"
48    if [[ "${JPEGXL_PUSH:-}" == "1" ]]; then
49      echo "sudo docker push ${tag}" >&2
50      sudo docker push "${tag}"
51      # The RepoDigest is only created after it is pushed.
52      local fulltag=$(sudo docker inspect --format="{{.RepoDigests}}" "${tag}")
53      fulltag="${fulltag#[}"
54      fulltag="${fulltag%]}"
55      echo "Updating .gitlab-ci.yml to ${fulltag}" >&2
56      sed -E "s;${tag}@sha256:[0-9a-f]+;${fulltag};" \
57        -i "${MYDIR}/../.gitlab-ci.yml"
58    fi
59  fi
60}
61
62main() {
63  cd "${MYDIR}"
64  local target="${1:-}"
65
66  load_targets
67  if [[ -z "${target}" ]]; then
68    usage $0
69    exit 1
70  fi
71
72  if [[ "${target}" == "all" ]]; then
73    for target in "${TARGETS[@]}"; do
74      build_target "${target}"
75    done
76  else
77    for target in "$@"; do
78      build_target "${target}"
79    done
80  fi
81}
82
83main "$@"
84