#!/bin/bash

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S.%N') $*"
}

function cleanup_spdk_resources() {
    log "Caught termination signal. Cleaning up SPDK resources..."

    local v2_devices=($(get_v2_devices))
    for device in "${v2_devices[@]}"; do
        dmsetup remove "$device"
        log "Removed device-mapper device: $device"

        device_file="/host/dev/longhorn/$device"
        rm "$device_file"
        log "Removed device file: $device_file"
    done

    log "Sending SIGTERM to go-spdk-helper to stop spdk_tgt..."
    go-spdk-helper kill-instance --sig-name SIGTERM
    if [[ $? -ne 0 ]]; then
        log "Failed to send SIGTERM to go-spdk-helper"
    else
        log "Successfully sent SIGTERM to go-spdk-helper"
    fi
}

function get_v2_devices() {
    local dm_devices
    dm_devices=$(dmsetup ls 2>/dev/null | awk '{print $1}')
    local v2_devices=()

    if [[ ! -d /host/dev/longhorn/ ]]; then
        echo "${v2_devices[@]}"
        return
    fi

    local device_files
    device_files=$(ls /host/dev/longhorn/)

    for dm_device in $dm_devices; do
        for device_file in $device_files; do
            if [[ "$dm_device" == "$device_file" ]]; then
                v2_devices+=("$dm_device")
                break
            fi
        done
    done

    echo "${v2_devices[@]}"
}

cleanup_spdk_resources
