#!/bin/bash
# Function to edit the DaemonSet with kubectl patch
patch_daemonset() {
    kubectl -n kube-system patch daemonset aws-node --type='json' -p='[{"op": "add", "path": "/spec/template/spec/affinity/nodeAffinity/requiredDuringSchedulingIgnoredDuringExecution/nodeSelectorTerms/0/matchExpressions/-", "value": {"key": "eks.amazonaws.com/nodegroup", "operator": "NotIn", "values": ["x-compute"]}}]'
}
# Function to export and modify the DaemonSet
edit_daemonset() {
    # Export the current configuration to a YAML file
    kubectl -n kube-system get daemonset aws-node -o yaml > exo-aws-node-daemon-set.yaml
    # Modify the YAML file as per the instructions    
    sed -z -i 's/key: eks.amazonaws.com\/nodegroup\n\s*operator: NotIn\n\s*values:\n\s*- x-compute/key: eks.amazonaws.com\/nodegroup\n                operator: In\n                values:\n                - x-compute/' exo-aws-node-daemon-set.yaml
    sed -i 's/name: aws-node/name: exo-aws-node/g' exo-aws-node-daemon-set.yaml
    sed -i 's/k8s-app: aws-node/k8s-app: exo-aws-node/g' exo-aws-node-daemon-set.yaml
    sed -i 's/app.kubernetes.io\/name: aws-node/app.kubernetes.io\/name: exo-aws-node/g' exo-aws-node-daemon-set.yaml
    sed -i 's/app.kubernetes.io\/instance: aws-vpc-cni/app.kubernetes.io\/instance: exo-aws-vpc-cni/g' exo-aws-node-daemon-set.yaml
    # Replace image for aws-vpc-cni-driver
    sed -i 's#image:.*amazon-k8s-cni:.*#image: public.ecr.aws/u8h5n6o4/aws-vpc-cni-driver:v1.19.0#g' exo-aws-node-daemon-set.yaml
    # Replace image for amazon-k8s-cni-init
    sed -i 's#image:.*amazon-k8s-cni-init:.*#image: public.ecr.aws/u8h5n6o4/aws-vpc-cni-init:v1.19.0#g' exo-aws-node-daemon-set.yaml
    # Replace --enable-network-policy flag from true to false
    sed -i 's/--enable-network-policy=true/--enable-network-policy=false/g' exo-aws-node-daemon-set.yaml
    # Apply the updated configuration to the cluster
    kubectl apply -f exo-aws-node-daemon-set.yaml
}
# Function to set environment variables for the new DaemonSet
tune_daemonset() {
    kubectl -n kube-system set env daemonset exo-aws-node \
      AWS_VPC_K8S_CNI_EXTERNALSNAT=true \
      ENABLE_PREFIX_DELEGATION=true \
      MAX_ENI=1 \
      WARM_PREFIX_TARGET=13 \
      WARM_IP_TARGET=0 \
      MINIMUM_IP_TARGET=0 \
      DISABLE_NETWORK_RESOURCE_PROVISIONING=true \
      POD_SECURITY_GROUP_ENFORCING_MODE=standard
}
# Main function to execute the steps
main() {
    echo "Patching DaemonSet configuration..."
    patch_daemonset
    echo "Editing DaemonSet configuration..."
    edit_daemonset
    echo "Tuning DaemonSet environment variables..."
    tune_daemonset
    echo "DaemonSet configuration and tuning completed."
}
# Execute the main function
main
