#!/bin/bash

# Define the file that stores the counter

PLUGIN_DTATA_DIR="/Library/Application Support/Logi/LogiPluginService/PluginData"
COUNTER_DIR="$PLUGIN_DTATA_DIR/AdobePlugins/Cache"

CONTROL_SURFACE_COUNTER_FILE="$COUNTER_DIR/ControlSurfaceCounter.txt"
CONTROL_SURFACE_LOCK_FILE="$CONTROL_SURFACE_COUNTER_FILE.lock"

acquire_lock() {
    lock_file=$1
    if [ ! -f "$lock_file" ]; then
        if [ ! -d "$COUNTER_DIR" ]; then
            mkdir -p "$COUNTER_DIR"
        fi
        touch "$lock_file"
        return 0
    else
        return 1
    fi
}

release_lock() {
    lock_file=$1
    rm -f "$lock_file"
}

increment_counter() {
    counter_file=$1
    if [ ! -f "$counter_file" ]; then
        if [ ! -d "$COUNTER_DIR" ]; then
            mkdir -p "$COUNTER_DIR"
        fi
        echo 1 > "$counter_file"

        echo "Plugins counter initialized with value: 1"
    else
        local current_counter=$(cat "$counter_file")
        local new_counter=$((current_counter + 1))
        echo $new_counter > "$counter_file"
        echo "Plugins counter incremented: $new_counter"
    fi
}

decrement_counter() {
    counter_file=$1
    if [ -f "$counter_file" ]; then
        local current_counter=$(cat "$counter_file")
        local new_counter=$((current_counter - 1))
        if [ "$new_counter" -le 0 ]; then
            rm "$counter_file"
            echo "Plugins counter is 0 or less. Counter file removed."
        else
            echo $new_counter > "$counter_file"
            echo "Plugins counter decremented: $new_counter"
        fi
    else
        echo "Plugins counter file not found."
    fi
}

increment_control_surface_counter() {
    if acquire_lock "$CONTROL_SURFACE_LOCK_FILE"; then
        increment_counter "$CONTROL_SURFACE_COUNTER_FILE"
        release_lock "$CONTROL_SURFACE_LOCK_FILE"
    fi
}

decrement_control_surface_counter() {
    if acquire_lock "$CONTROL_SURFACE_LOCK_FILE"; then
        decrement_counter "$CONTROL_SURFACE_COUNTER_FILE"
        release_lock "$CONTROL_SURFACE_LOCK_FILE"
    fi
}

control_surface_references_count() {
    local current_counter=0
    if acquire_lock "$CONTROL_SURFACE_LOCK_FILE"; then
        if [ -f "$CONTROL_SURFACE_COUNTER_FILE" ]; then
            current_counter=$(cat "$CONTROL_SURFACE_COUNTER_FILE")
        fi
        release_lock "$CONTROL_SURFACE_LOCK_FILE"
    fi

    return $current_counter
}

export -f control_surface_references_count
export -f increment_control_surface_counter
export -f decrement_control_surface_counter