#!/bin/bash
revert=0
user_units=()

if [[ "$1" == "--revert" ]]; then
    revert=1
fi

set -u

while read -r unitpath; do
    IFS='/' read -ra unitarray <<< "$unitpath"

    # If the path leads to a drop-in file, a dir or a symlink, we skip it
    # Example of a valid entry: usr/lib/systemd/system/user@.service
    if (( ${#unitarray[@]} > 5 )) || [[ ! -f $unitpath || -L $unitpath ]]; then
        continue
    fi

    type=${unitarray[3]}
    unit=${unitarray[4]}

    case $type in
        system)
            if (( revert )); then
                /usr/bin/systemctl revert "$unit"
            fi

            # Manager will be reloaded by post hook, so no explicit reload here
            /usr/bin/systemctl disable --now --no-reload --no-warn "$unit"
            ;;
        user)
            if (( revert )); then
                /usr/bin/systemctl --global revert "$unit"
            fi

            /usr/bin/systemctl --global disable --no-warn "$unit"
            user_units+=("'${unit/@/@*}'")
            ;;
    esac
done

if (( ${#user_units[@]} > 0 )); then
    printf "==> %s user unit(s) being removed\n" "${#user_units[@]}"
    printf "  -> To stop them in current user manager, run \"systemctl --user stop %s\"\n" "${user_units[*]}"

    if (( revert )); then
        printf "  -> To revert changes to them, run \"systemctl --user revert %s\"\n" "${user_units[*]}"
    fi
fi

# vim: set ft=sh ts=4 sw=4 et:
