#!/bin/php

<?php
#
# kubectl-create-conf.php
# A PHP script that creates a Service Account and extracts to corresponding
# token to create a kubeconfig.yaml file
# https://cylab.be/blog/178/create-and-use-kubeconfigyaml
# https://gitlab.cylab.be/-/snippets/1
#
$options = getopt("", ["name:", "namespace:"]);

// NAME and NAMESPACE
$NAMESPACE = $options["namespace"];
$NAME = $options["name"];

// SERVICE ACCOUNT and TOKEN
$tmpl = <<<EOT
apiVersion: v1
kind: ServiceAccount
metadata:
  name: $NAME
EOT;
$cmd = "echo '$tmpl' | kubectl apply --namespace $NAMESPACE -f -";
$out = shell_exec($cmd);

$cmd = "kubectl get sa $NAME --namespace $NAMESPACE -o json";
$out = shell_exec($cmd);
$json = json_decode($out, true);
$secret_name = $json["secrets"][0]["name"];

$cmd = "kubectl get secret $secret_name --namespace $NAMESPACE -o json";
$out = shell_exec($cmd);
$json = json_decode($out, true);
$TOKEN = base64_decode($json["data"]["token"]);

// SERVER and CERTIFICATE
$cmd = "kubectl config view --flatten -o json";
$out = shell_exec($cmd);
$json = json_decode($out, true);

$SERVER = $json["clusters"][0]["cluster"]["server"];
$CERTIFICATE = $json["clusters"][0]["cluster"]["certificate-authority-data"];

// TEMPLATE
$conf = <<<EOT
apiVersion: v1
kind: Config
users:
- name: $NAME
  user:
    token: $TOKEN
clusters:
- name: k8s
  cluster:
    certificate-authority-data: $CERTIFICATE
    server: $SERVER
contexts:
- name: $NAME@$NAMESPACE
  context:
    cluster: k8s
    user: $NAME
    namespace: $NAMESPACE
current-context: $NAME@$NAMESPACE

EOT;

echo $conf;