#!/usr/bin/env sh
#
# SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
#
# SPDX-License-Identifier: Apache-2.0

set -e

repo_root_dir="$(realpath $1)"
repo_base="$2"
repo_name="$3"

apk update
apk add --no-cache \
    ca-certificates \
    make \
    bash \
    git \
    curl \
    openssl \
    tar \
    gzip \
    sed \
    jq

# create virtual package with the dev tools
echo "Installing dev tools in a virtual package"
apk add --no-cache --virtual .build-deps \
    gcc \
    go \
    musl-dev

GOLANG_VERSION="$(sed -rn 's/FROM (eu\.gcr\.io\/gardener-project\/3rd\/golang|golang):([^ ]+).*/\2/p' < "$repo_root_dir/Dockerfile")"

# As we cannot expect alpine to provide and maintain all golang versions via apk, we need to find another way to install the required golang version.
# Alpine is using musl-libc instead of glibc, therefore we cannot use the available pre-built binaries from golang, but have to build them ourselves from source.
# refs:
#   - https://stackoverflow.com/a/45987284
#   - https://github.com/docker-library/golang/blob/f300e60ca19c3b98cfcf01ca112af2ac10104320/1.16/alpine3.14/Dockerfile
echo "Downloading go src $GOLANG_VERSION"
rm -rf /usr/local/go
wget -q -O - "https://golang.org/dl/go$GOLANG_VERSION.src.tar.gz" | tar zx -C /usr/local

# Configure golang environment
echo "Building and installing go $GOLANG_VERSION"
export \
  PATH="/usr/local/go/bin":$PATH \
  GOARCH="$(go env GOARCH)" \
  GOOS="$(go env GOOS)" \
  GOROOT_BOOTSTRAP="$(go env GOROOT)"
export GOHOSTOS="$GOOS" \
  GOHOSTARCH="$GOARCH"
cd /usr/local/go/src
echo "Executing make on go $GOLANG_VERSION"
./make.bash

echo "Deleting the virtual package for go"
apk del --no-network .build-deps

export GOROOT="/usr/local/go"
export GOPATH="$(mktemp -d)"
export GOBIN="$GOPATH/bin"
export PATH="$GOBIN:$PATH"

REPO_BASE="$GOPATH/src/$repo_base"
mkdir -p "$REPO_BASE"
REPO_PATH="$REPO_BASE/$repo_name"
cp -R "$repo_root_dir" "$REPO_PATH"

current_dir="$(pwd)"
cd "$REPO_PATH"

if make -n install-requirements &>/dev/null; then
  make install-requirements
else
  echo "skipping optional 'make install-requirements' as it is not present"
fi

cd "$current_dir"

echo "$EFFECTIVE_VERSION" > "$REPO_PATH/VERSION"
cur_dir="$(pwd)"
cd "$REPO_PATH"
if ! make generate; then
  cd "$cur_dir"
  exit 1
fi
cd "$cur_dir"
cp -RT "$REPO_PATH/" "$repo_root_dir/"
