#!/bin/bash
set -e

source $(dirname $0)/version

cd $(dirname $0)/..

mkdir -p bin
cd ./cmd/rancherd

RUNTIME_TAG=$TAG
if [ ! -z $DRONE_BRANCH ] && [ -z $DRONE_TAG ];then
  RUNTIME_TAG=${DRONE_BRANCH/release\//}-${DRONE_COMMIT}
fi
echo "RUNTIME_TAG: $RUNTIME_TAG"

RKE2_VERSION=$(grep 'ARG RKE2_VERSION=' ../../package/Dockerfile.runtime | sed 's/.*RKE2_VERSION=//')
# These variables come from https://github.com/rancher/rke2/blob/$RKE2_VERSION/scripts/version.sh for the RKE2_VERSION
RKE2_ETCD_VERSION=${RKE2_ETCD_VERSION:-v3.4.13-k3s1}
RKE2_IMAGE_BUILD_VERSION=${RKE2_IMAGE_BUILD_VERSION:-build20210223}
RKE2_PAUSE_VERSION=${RKE2_PAUSE_VERSION:-3.2}

go build -o ../../bin/rancherd-${ARCH} \
    -ldflags '-w -s -extldflags "-static"
    -X github.com/rancher/rke2/pkg/images.KubernetesVersion='${RKE2_VERSION}'-'${ARCH}'
    -X github.com/rancher/rke2/pkg/images.DefaultEtcdImage=rancher/hardened-etcd:'${RKE2_ETCD_VERSION}'-'${RKE2_IMAGE_BUILD_VERSION}'
    -X github.com/rancher/rke2/pkg/images.DefaultKubernetesImage=rancher/hardened-kubernetes:'${RKE2_VERSION}'
    -X github.com/rancher/rke2/pkg/images.DefaultPauseImage=rancher/pause:'${RKE2_PAUSE_VERSION}'
    -X github.com/rancher/rke2/pkg/images.DefaultRuntimeImage=rancher/rancher-runtime:'${RUNTIME_TAG}'
    -X github.com/rancher/k3s/pkg/version.Program=rke2
    -X github.com/rancher/k3s/pkg/version.Version='$RUNTIME_TAG \
    -tags "netgo osusergo selinux no_stage static_build sqlite_omit_load_extension"
if [ "$ARCH" = "amd64" ]; then
    cp ../../bin/rancherd-${ARCH} ../../bin/rancherd
fi

cd ../..
./scripts/chart/build cmd/rancherd/chart
./scripts/chart/package

sed -e "s|%{CHART_CONTENT}%|$(base64 -w0 ./bin/chart/*/rancher-${CHART_VERSION}.tgz)|g" ./scripts/rancher.yaml.tmpl > ./bin/rancher.yaml
cp ./scripts/rancher-namespace.yaml.tmpl ./bin/rancher-namespace.yaml

