#!/usr/bin/env bash

driverName="stor.csi.k8s.io"
driverNamespace="default"
iscsiOnHost="false"
snapshotCRDs="false"

for arg in "$@"
do
    case $arg in
        --include-snapshot-crd)
        snapshotCRDs="true"
        shift
        ;;
        --driver-name=*)
        driverName="${arg#*=}"
        shift
        ;;
        --driver-namespace=*)
        driverNamespace="${arg#*=}"
        shift
        ;;
        --iscsi-on-host)
        iscsiOnHost="true"
        shift
        ;;
        *)
        echo "Unknown option: $arg"
        exit 1
        ;;
    esac
done

tmpDir="./tmp-${driverNamespace}"

if [ "$driverNamespace" = "" ]; then
    echo "Error: Value '' at 'driver-namespace' failed to satisfy constraint: Argument must not be ''."
    exit 1
fi
if [ "$driverName" = "" ]; then
    echo "Error: Value '' at 'driver-name' failed to satisfy constraint: Argument must not be ''."
    exit 1
fi

setup_csi_files() {
    local snapshotCRDs=$1
    local iscsiOnHost=$2
    local driverNamespace=$3
    local driverName=$4

    if [ -d $tmpDir ]; then
        rm -rf "$tmpDir"/*yaml
    else
        mkdir -p $tmpDir
    fi
    cp -f ./csi-plugin-conf/csi-configMap.yaml $tmpDir
    cp -f ./csi-plugin-conf/csi-secret-decrypt.yaml $tmpDir
    cp -f ./csi-plugin-conf/csi-secret.yaml $tmpDir
    cp -f ./csi-storplugin-controller-snapshot.yaml $tmpDir
    cp -f ./csi-storplugin-controller.yaml $tmpDir
    cp -f ./csi-storplugin-rbac-snapshot.yaml $tmpDir
    cp -f ./csi-storplugin-rbac.yaml $tmpDir
    cp -f ./csi-snapshot-updater.yaml $tmpDir
    cp -f ./csi-snapshot-updater-rbac.yaml $tmpDir    

    if [ "$snapshotCRDs" = "true" ]; then
        cp -f ./snapshot-crds/* $tmpDir
    fi
    if [ "$iscsiOnHost" = "true" ]; then
        cp -f ./csi-plugin-conf/csi-cm-command.yaml $tmpDir
        cp -f ./csi-storplugin-node-iscsi-on-host.yaml $tmpDir
    else
        cp -f ./csi-storplugin-node.yaml $tmpDir
    fi

    local driverNameSuffix=""
    if [ "$driverNamespace" != "default" ]; then
        driverNameSuffix="-$driverNamespace"
    fi

    K8S_VERSION=$(kubectl version --short 2>&1 | grep -i server | awk '{print $3}' | cut -d. -f1,2)

    if [[ "$K8S_VERSION" > "v1.21" ]] || [[ "$K8S_VERSION" == "v1.21" ]]; then
        batchApiVersion="v1"
    else
        batchApiVersion="v1beta1"
    fi

    for file in "$tmpDir"/*; do
        if [ -d "$file" ]; then
            continue
        else
            sed -i "s/@DRIVER_NAMESPACE_SUFFIX@/$driverNameSuffix/g" "$file"
            sed -i "s/@DRIVER_NAMESPACE@/$driverNamespace/g" "$file"
            sed -i "s/@DRIVER_NAME@/$driverName/g" "$file"
            sed -i "s/@BATCH_API_VERSION@/$batchApiVersion/g" "$file"
        fi
    done
}

setup_csi_files $snapshotCRDs $iscsiOnHost $driverNamespace $driverName

if [ "$iscsiOnHost" != "true" ]; then
    echo -e "\nstop host iscsi"
    chmod 777 tool_st.sh
    ./tool_st.sh
    chmod 777 csi-plugin-conf/create-multipath-conf.sh
    ./csi-plugin-conf/create-multipath-conf.sh $driverNamespace
fi

function apply_dir(){
    local dir_path="$1"
    for file in "$dir_path"/*; do
        suffix="${file##*.}"
        if [ "$suffix" = "yaml" ]; then
            echo "  [do] kubectl apply -f $file"
            kubectl apply -f "$file"
        fi
    done
}

echo -e "\nstart applying yaml......"
apply_dir $tmpDir
rm -rf $tmpDir
echo -e "end applying yaml !!!"
# check csi-stor-plugin pod status
echo -e "\ncheck pod status ......"

expected_running_pods=1
cnt=0
function check_pod(){
  tmp="^$1.*Running.*"
  while [ $(kubectl get pods -n $2 2>/dev/null | grep $tmp | wc -l) -lt ${expected_running_pods} ]; do
    if [ $cnt -gt 30 ]; then
        echo "$(kubectl get pods -n $2 2>/dev/null | grep '^{"$1"}.* Running ' | wc -l) running pods:"
        kubectl describe pods -n $2

        echo >&2 "ERROR: "$1" deployment not ready after over 5min"
        exit 1
    fi
    echo $(date +%H:%M:%S) "waiting for "$1" to complete, attempt #$cnt"
    cnt=$(($cnt + 1))
    sleep 10
  done
  echo -e "$1 checking success !!!"
}
#check sidecar pod
check_pod csi-storplugin-controller $driverNamespace

eval $(kubectl get daemonset -n $driverNamespace | grep csi | awk '{printf("expected_running_pods=%s;",$2)}')
echo "daemonset csi-storplugin-node count:  $expected_running_pods"
check_pod csi-storplugin-node $driverNamespace
echo "deployment csi-storplugin-node success !!!"