#!/bin/bash
# Function to edit the DaemonSet with kubectl patch
patch_daemonset() {
    FILE="csi-node-daemon-set.json"
    kubectl -n kube-system get daemonset ebs-csi-node -o json > $FILE
    jq '.spec.template.spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms
      |= map(
          .matchExpressions |= map(
            select(
              .key != "eks.amazonaws.com/nodegroup" 
              or .operator != "NotIn" 
              or (.values | length != 1 or .[0] != "x-compute")
            )
          )
        )
      | .spec.template.spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchExpressions += [{
          "key": "eks.amazonaws.com/nodegroup",
          "operator": "NotIn",
          "values": ["x-compute"]
        }]
    ' $FILE > $FILE.tmp && mv $FILE.tmp $FILE
    kubectl apply -f $FILE
    rm $FILE
}

# Function to export and modify the DaemonSet
edit_daemonset() {
    FILE="exo-ebs-csi-node-daemon-set.json"
    # Export the current configuration to a JSON file
    kubectl -n kube-system get daemonset ebs-csi-node -o json > $FILE
    jq 'del(.metadata.resourceVersion, .metadata.uid)' "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"
    # Change nodeAffinity to schedule on x-compute nodes
    jq '(.spec.template.spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[].matchExpressions[]) 
        |= if .key == "eks.amazonaws.com/nodegroup" 
            and .operator == "NotIn" 
            and (.values | length > 0) 
            and .values[0] == "x-compute" 
            then .operator = "In" 
            else . 
        end
    ' $FILE > "$FILE.tmp" && mv "$FILE.tmp" $FILE
    # Modify the JSON file as per the instructions
    sed -i 's/\"name\": \"ebs-csi-node\"/\"name\": \"exo-ebs-csi-node\"/g' $FILE
    sed -i 's/\"app\": \"ebs-csi-node\"/\"app\": \"exo-ebs-csi-node\"/g' $FILE
    sed -i 's/\"app.kubernetes.io\/name\": \"aws-ebs-csi-driver\"/\"app.kubernetes.io\/name\": \"exo-aws-ebs-csi-driver\"/g' $FILE
    sed -i 's/\"app.kubernetes.io\/component\": \"csi-driver\"/\"app.kubernetes.io\/component\": \"exo-csi-driver\"/g' $FILE
    jq '(.spec.template.spec.containers[].image) 
        |= if test("aws-ebs-csi-driver") 
            then "public.ecr.aws/u8h5n6o4/aws-ebs-csi-driver:v1.37.0" 
            else . 
        end
    ' $FILE > $FILE.tmp && mv $FILE.tmp $FILE
    # Apply the updated configuration to the cluster
    kubectl apply -f $FILE
    rm $FILE
}

# Function to set environment variables for the new DaemonSet
tune_daemonset() {
    echo "pass"
}

# 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