#!/bin/sh

set -e

# Update cache of .desktop file MIME types. Non-fatal since it's just a cache.
update-desktop-database > /dev/null 2>&1 || true

create_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
    # Launcher file must set execute bit
    install -m 755 -o "$uid:$gid" "/usr/share/applications/${1}" "$xdg_dirs"
    echo "Created launcher on $xdg_dirs"
  done
}

create_launcher_all_users "tuxpaint.desktop"
