#!/bin/bash
MACHINE_IP=$1
export SOPS_AGE_KEY_FILE=wbc-dev-cluster-base.age-key

if expr "${MACHINE_IP}" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
	sops exec-file secrets.yaml 'talosctl gen config --with-secrets {} wbc-dev-cluster https://'${MACHINE_IP}':6443 --config-patch @patches/controlplane/controlplane.yaml --output-types controlplane,talosconfig' 
	shift
	talosctl apply -f controlplane.yaml -n ${MACHINE_IP} -e ${MACHINE_IP} --insecure
	until talosctl -e ${MACHINE_IP} -n ${MACHINE_IP} --talosconfig talosconfig bootstrap; do echo "sleeping for reboot"; sleep 5 done
	until talosctl -e ${MACHINE_IP} -n ${MACHINE_IP} --talosconfig talosconfig health; do echo "sleeping for post-apply"; sleep 5 done
	talosctl -e ${MACHINE_IP} -n ${MACHINE_IP} --talosconfig talosconfig kubeconfig --merge=false --force-context-name=wbc-dev kubeconfig
	rm talosconfig controlplane.yaml
	echo "Cluster created - files in current directory outputted:"
	echo " - kubeconfig - config file for kubectl to access the cluster."
else
	echo pass machine ip as first arg.
fi
