#!/bin/bash

# run as user 

# USAGE: 
# without argument defaults to `code`
# with single argument giving the name of the clone of code. 
# Currently we use `CODE` for the flatpack version and we use `codium`. 
# This is used by eu.simuline:qMngmnt:0.0.6


# use `code` by default 
case $# in 
  0)
    code="code"
    ;;
  1)
    code=$1
    ;;
  *)
    echo "Expected 0 or 1 arguments, found $#."
    exit 1
    ;;
esac

# xargs -L 1 means: one line after the other 
#$code --list-extensions | xargs -r -L 1 $code --uninstall-extension --force

# reads the extension identifiers into $extensions
mapfile -t extensions < <(code --list-extensions | grep "\.")


for ext in "${extensions[@]}"; do
    # --disable-gpu, to save load on X-Server 
    pgrep -f "uninstall-extension $ext"
    $code --uninstall-extension "$ext" --force --disable-gpu
    
    # wait the uninstall process to disappear 
    SLEEP=1
    MAX_COUNT=10
    COUNT=0
    while pgrep -f "uninstall-extension $ext" > /dev/null && [ $COUNT -lt $MAX_COUNT ]; do
        sleep $SLEEP
        ((COUNT++))
    done
    # observe all zero. maybe the expression is not correct or the uninstall is too fast. 
    echo "$COUNT"

    # SCHRITT C: Check auf verwaiste Language-Server (Zombies)
    # Falls die Extension einen Server gestartet hat, der noch im Ordner lebt:
    # if pgrep -f ".vscode/extensions/$ext" > /dev/null; then
    #     echo "[WARN] Verwaister Prozess gefunden! Erzwungener Abbruch..."
    #     pkill -9 -f ".vscode/extensions/$ext"
    # fi


done

