#!/usr/bin/env bash
set -euo pipefail

REGISTRY_HOST="registry.juwan.xhttp.zip"
CNPG_VERSION="1.29.0"
REDPANDA_OP_VERSION="v26.1.3"
REDIS_OP_VERSION="0.24.0"
MONGODB_OP_VERSION="1.8.0"

MODE="${1:-server}"

if [ "$MODE" != "server" ] && [ "$MODE" != "agent" ]; then
	echo "usage: $0 [server|agent]" >&2
	exit 1
fi

if [ ! -f /root/registry-password ]; then
	echo "need /root/registry-password (zot admin password)" >&2
	exit 1
fi

K01_DIR="$(cd "$(dirname "$0")" && pwd)"

write_registries() {
	mkdir -p /etc/rancher/k3s
	cat > /etc/rancher/k3s/registries.yaml <<EOF
mirrors:
  ${REGISTRY_HOST}:
    endpoint:
      - "https://${REGISTRY_HOST}"
configs:
  ${REGISTRY_HOST}:
    auth:
      username: admin
      password: $(cat /root/registry-password)
EOF
}

if [ "$MODE" = "agent" ]; then
	if [ -z "${K3S_URL:-}" ] || [ -z "${K3S_TOKEN:-}" ]; then
		echo "agent mode requires K3S_URL and K3S_TOKEN env" >&2
		echo "  on the server:  cat /var/lib/rancher/k3s/server/node-token" >&2
		echo "  then on agent:  K3S_URL=https://<server-ip>:6443 K3S_TOKEN=<token> $0 agent" >&2
		exit 1
	fi
	write_registries
	if ! command -v k3s-agent >/dev/null 2>&1 && ! systemctl is-active --quiet k3s-agent; then
		curl -sfL https://get.k3s.io | K3S_URL="$K3S_URL" K3S_TOKEN="$K3S_TOKEN" sh -
	else
		systemctl restart k3s-agent
	fi
	echo
	echo "k3s agent joined ${K3S_URL}"
	exit 0
fi

if ! systemctl is-active --quiet k3s; then
	curl -sfL https://get.k3s.io | \
		INSTALL_K3S_EXEC="--disable=traefik --write-kubeconfig-mode=644" \
		sh -
fi

if ! command -v helm >/dev/null 2>&1; then
	curl -fsSL https://packages.buildkite.com/helm-linux/helm-debian/gpgkey | \
		gpg --dearmor -o /usr/share/keyrings/helm.gpg
	echo "deb [signed-by=/usr/share/keyrings/helm.gpg] https://packages.buildkite.com/helm-linux/helm-debian/any/ any main" \
		> /etc/apt/sources.list.d/helm-stable-debian.list
	apt-get update
	apt-get install -y helm
fi

write_registries
systemctl restart k3s

export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
until kubectl get nodes >/dev/null 2>&1; do sleep 2; done

kubectl apply -f "${K01_DIR}/base/"

kubectl apply --server-side --force-conflicts -f \
	"https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v${CNPG_VERSION}/cnpg-${CNPG_VERSION}.yaml"
kubectl -n cnpg-system set resources deploy/cnpg-controller-manager \
	--requests=cpu=30m,memory=40Mi --limits=cpu=200m,memory=200Mi

kubectl create namespace redpanda 2>/dev/null || true

helm repo add ot-helm https://ot-container-kit.github.io/helm-charts/ 2>/dev/null || true
helm repo add mongodb https://mongodb.github.io/helm-charts 2>/dev/null || true
helm repo add redpanda https://charts.redpanda.com 2>/dev/null || true
helm repo update

helm upgrade --install redpanda-controller redpanda/operator \
	--version "${REDPANDA_OP_VERSION}" \
	--namespace redpanda \
	--set crds.enabled=true \
	--set resources.requests.cpu=30m \
	--set resources.requests.memory=100Mi \
	--set resources.limits.cpu=500m \
	--set resources.limits.memory=300Mi \
	--set-json 'livenessProbe={"initialDelaySeconds":30,"periodSeconds":60,"timeoutSeconds":10,"failureThreshold":5}' \
	--set-json 'readinessProbe={"initialDelaySeconds":15,"periodSeconds":30,"timeoutSeconds":10,"failureThreshold":5}'

helm upgrade --install redis-operator ot-helm/redis-operator \
	--version "${REDIS_OP_VERSION}" \
	--namespace redis-operator --create-namespace \
	--set resources.requests.cpu=20m \
	--set resources.requests.memory=30Mi \
	--set resources.limits.cpu=500m \
	--set resources.limits.memory=150Mi

helm upgrade --install mongodb-kubernetes mongodb/mongodb-kubernetes \
	--version "${MONGODB_OP_VERSION}" \
	--namespace mongodb-operator --create-namespace \
	--set operator.watchNamespace=juwan \
	--set operator.resources.requests.cpu=30m \
	--set operator.resources.requests.memory=50Mi \
	--set operator.resources.limits.cpu=500m \
	--set operator.resources.limits.memory=200Mi

kubectl -n cnpg-system rollout status deploy/cnpg-controller-manager --timeout=300s
kubectl -n redpanda rollout status deploy/redpanda-controller-operator --timeout=300s
kubectl -n redis-operator rollout status deploy/redis-operator --timeout=300s
kubectl -n mongodb-operator rollout status deploy/mongodb-kubernetes-operator --timeout=300s

echo
echo "k3s server + 4 operators ready"
echo "node token: $(cat /var/lib/rancher/k3s/server/node-token)"
