# rancher-overlay.yaml - Universal Rancher overlay
variant: flatcar
version: 1.0.0
storage:
  files:
    - path: /etc/hostname
      mode: 0644
      overwrite: true
      contents:
        inline: rancher-server
    - path: /opt/setup-rancher.sh
      mode: 0755
      contents:
        inline: |
          #!/bin/bash
          # Detect k8s distribution and set paths
          if [ -d "/var/lib/rancher/rke2" ]; then
            KUBECONFIG="/etc/rancher/rke2/rke2.yaml"
            # Ensure RKE2 is started
            systemctl start rke2-server.service
          elif [ -d "/var/lib/rancher/k3s" ]; then
            KUBECONFIG="/etc/rancher/k3s/k3s.yaml"
            # Ensure K3s is started
            systemctl start k3s
          else
            echo "No supported kubernetes distribution found"
            exit 1
          fi

          # Export kubeconfig for helm and kubectl
          export KUBECONFIG
          # Export helm_install_dir for helm
          export HELM_INSTALL_DIR=/opt/bin

          # Wait for cluster to be ready
          while ! kubectl get nodes; do sleep 5; done

          # Install Helm if not present
          if ! command -v helm &> /dev/null; then
            curl -sfL https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | sh -
          fi

          # Install cert-manager
          kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.3/cert-manager.yaml

          # Wait for cert-manager
          kubectl -n cert-manager wait --for=condition=ready pod -l app=cert-manager --timeout=60s

          # Install Rancher
          helm repo add rancher-stable https://releases.rancher.com/server-charts/stable
          helm repo update

          kubectl create namespace cattle-system
          helm install rancher rancher-stable/rancher \
            --namespace cattle-system \
            --set hostname=$(hostname | cut -d' ' -f1).sslip.io \
            --set bootstrapPassword=adminadmin \
            --set replicas=1

systemd:
  units:
    - name: rancher-setup.service
      enabled: true
      contents: |
        [Unit]
        Description=Rancher Setup
        After=network-online.target
        # Generic condition to wait for either k3s or rke2
        After=k3s.service rke2-server.service
        Requires=network-online.target

        [Service]
        Type=oneshot
        ExecStart=/opt/setup-rancher.sh
        RemainAfterExit=yes

        [Install]
        WantedBy=multi-user.target
