#!/usr/bin/env bash

# Synchs the release-next branch to master and then triggers CI
# Usage: update-to-head.sh

set -ex
REPO_NAME=${REPO_NAME:-tektoncd-pipeline}
TODAY=`date "+%Y%m%d"`
OPENSHIFT_REMOTE=${OPENSHIFT_REMOTE:-openshift}
LABEL=nightly-ci

# Reset release-next to upstream/main.
git fetch upstream main
git checkout upstream/main --no-track -B release-next

# Update openshift's master and take all needed files from there.
git fetch ${OPENSHIFT_REMOTE} master
git checkout FETCH_HEAD openshift Makefile OWNERS_ALIASES OWNERS
make generate-dockerfiles

git add openshift OWNERS_ALIASES OWNERS Makefile
git commit -m ":open_file_folder: Update openshift specific files."

if [[ -d openshift/patches ]];then
    for f in openshift/patches/*.patch;do
        [[ -f ${f} ]] || continue
        git am ${f}
    done
fi

# Caution: Need to be applied after the patches
#
# Replace docker.io images with a mirror which doesn't get rate limited.
# prefer to use ecr since closest to our install but sometime gcr.io is better,
# for example on busybox the ecr image (public.ecr.aws/runecast/busybox)
# doesn't have latest tags while the gcr one does.
find . -type f -name '*.go' -o -name '*.yaml' | \
    xargs -P6 -r sed -E -i \
          -e 's,image: ubuntu$,image: public.ecr.aws/ubuntu/ubuntu:latest,' -e 's,"ubuntu","public.ecr.aws/ubuntu/ubuntu",g' \
          -e 's,"busybox","gcr.io/google-containers/busybox",g' -e 's,image: busybox$,image: gcr.io/google-containers/busybox,'

git commit -a -m ":robot: Switching image from docker.io to public cloud providers registry"

# set feature-flags to preserve defaults in GA release 1.4.x
# ref: https://github.com/tektoncd/pipeline/pull/3878
sed -i -e 's/\(disable-home-env-overwrite\).*/\1: "false"/' \
    -e 's/\(disable-working-directory-overwrite\).*/\1: "false"/' config/config-feature-flags.yaml

git commit -a -m ":robot: Setting feature flags as per Red Hat OpenShift Pipelines defaults"

git push -f ${OPENSHIFT_REMOTE} release-next
