#!/bin/sh

set -e

update-desktop-database > /dev/null 2>&1 || true

delete_launcher_all_users()
{
  # $1: name of the .desktop file
  # Enumerate all users in system
  getent passwd | while IFS=: read -r name password uid gid gecos home shell; do
    # Only users with a login shell
    if [ -z "$shell" ] || [ "$shell" = "/bin/false" ] || [ "$shell" = "/usr/sbin/nologin" ]; then
      continue
    fi
    # Only users that own their home directory
    if [ ! -d "$home" ] || [ "$(stat -c %u "$home")" != "$uid" ]; then
      continue
    fi
    # Find XDG user dirs config
    xdg_dirs="$home/.config/user-dirs.dirs"
    if [ ! -f "$xdg_dirs" ]; then
      continue
    fi
    # Get XDG_DESKTOP_DIR
    xdg_dirs="$home$(grep XDG_DESKTOP_DIR= $xdg_dirs |
                     cut -d '=' -f 2- |
                     sed 's/^"$HOME\(.*\)"$/\1/')"
    if [ ! -d "$xdg_dirs" ]; then
      continue
    fi
    # Remove launcher
    rm -rf "$xdg_dirs/${1}"
    echo "Deleted launcher on $xdg_dirs"
  done
}

delete_launcher_all_users "tuxpaint.desktop"
