#!/bin/bash
#
# Purpose : Put a website in GNOME's app grid as an app of its own: it opens
#           in its own window, without the browser's tabs and address bar, and
#           has its own icon in the dock. Adapted from Omarchy.

APPS="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
ICONS="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
# Chromium-based browsers, which can open a site as an app (--app)
APP_BROWSERS="${WEBAPP_BROWSERS:-helium-browser chromium google-chrome-stable brave vivaldi-stable microsoft-edge-stable}"

usage() {
  cat << EOF
Usage: webapp add <name> <url> [icon]   Add a web app; icon is an image's URL or file
       webapp remove <name>             Remove a web app
       webapp list                      List your web apps
       webapp open <url>                Open a site as an app

  webapp add "Nextcloud" https://nextcloud.example.com
EOF
}

# "My App" -> my-app
slug() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//'
}

desktop_file() {
  echo "$APPS/webapp-$(slug "$1").desktop"
}

# The browser command to open apps with: your default browser if it's
# Chromium-based, or else the first such browser installed
app_browser() {
  local default dir command
  default="$(xdg-settings get default-web-browser 2> /dev/null)"
  if [ -n "$default" ]; then
    for dir in "${XDG_DATA_HOME:-$HOME/.local/share}" ${XDG_DATA_DIRS//:/ } /usr/local/share /usr/share; do
      [ -f "$dir/applications/$default" ] || continue
      command="$(sed -nE 's/^Exec=([^ ]+).*/\1/p' "$dir/applications/$default" | head -n 1)"
      break
    done
    if [[ " $APP_BROWSERS " == *" ${command##*/} "* ]] && command -v "$command" > /dev/null; then
      echo "$command"
      return 0
    fi
  fi
  for command in $APP_BROWSERS; do
    command -v "$command" > /dev/null && { echo "$command"; return 0; }
  done
  return 1
}

# Chromium names an app's window after the site's host and path. Naming it in
# the launcher's StartupWMClass lets GNOME put the window under the launcher.
window_class() {
  local address host path
  address="${1#*://}"
  address="${address%%[?#]*}"
  host="${address%%/*}"
  path="${address:${#host}}"
  host="${host##*@}"
  host="${host%%:*}"
  printf 'chrome-%s_%s-Default\n' "${host,,}" "${path:-/}" | sed 's|/|_|g'
}

# Quote $1 as one argument of a desktop entry's Exec: in double quotes, with
# \ " ` $ backslashed, then % doubled and every \ doubled again, since Exec is
# itself an escaped string
exec_arg() {
  local arg="$1"
  arg="${arg//\\/\\\\}"
  arg="${arg//\"/\\\"}"
  arg="${arg//\`/\\\`}"
  arg="${arg//\$/\\\$}"
  arg="${arg//%/%%}"
  arg="${arg//\\/\\\\}"
  printf '"%s"' "$arg"
}

# Only http(s): a browser's --app runs javascript: and file: URLs as pages
check_url() {
  [[ "$1" =~ ^https?://[^[:space:]]+$ ]] || { echo "The address must start with https:// (or http://): $1" >&2; return 1; }
}

# Save the app's icon as $2 from an image's URL or file $1, or else from the
# site's apple-touch-icon. Prints the Icon= value to use.
fetch_icon() {
  local source="$1" name="$2" url="$3" origin tmp
  mkdir -p "$ICONS"
  tmp="$(mktemp)"
  if [ -n "$source" ] && [ -f "$source" ]; then
    cp "$source" "$tmp"
  elif [ -n "$source" ]; then
    curl -fsSL --max-time 15 -o "$tmp" "$source" 2> /dev/null
  else
    origin="$(sed -E 's#^(https?://[^/]+).*#\1#' <<< "$url")"
    curl -fsSL --max-time 15 -o "$tmp" "$origin/apple-touch-icon.png" 2> /dev/null
  fi
  if [ -s "$tmp" ] && [[ "$(file -b --mime-type "$tmp")" == image/* ]]; then
    mv -f "$tmp" "$ICONS/$name.png"
    gtk-update-icon-cache -q "${ICONS%/256x256/apps}" 2> /dev/null
    echo "$ICONS/$name.png"
  else
    rm -f "$tmp"
    [ -n "$source" ] && echo "Couldn't get an image from $source; using a plain icon." >&2
    echo "applications-internet"
  fi
}

add() {
  local name="$1" url="$2" icon_source="$3" file icon
  if [ -z "$name" ] || [ -z "$url" ]; then
    usage >&2
    return 2
  fi
  [ -n "$(slug "$name")" ] || { echo "Give the app a name with letters or numbers in it." >&2; return 1; }
  [[ "$name" != *$'\n'* ]] || { echo "The name must be on one line." >&2; return 1; }
  check_url "$url" || return 1
  app_browser > /dev/null || echo "Note: web apps open in a Chromium-based browser such as Helium, and none is installed. Until one is, this opens in your browser." >&2

  file="$(desktop_file "$name")"
  icon="$(fetch_icon "$icon_source" "webapp-$(slug "$name")" "$url")"
  mkdir -p "$APPS"
  # webapp open finds the browser each time, so changing browsers doesn't
  # break the launcher
  cat > "$file" << EOF
[Desktop Entry]
Type=Application
Name=$name
Comment=$url
Exec=$(exec_arg "$HOME/.local/bin/webapp") open $(exec_arg "$url")
Icon=$icon
StartupWMClass=$(window_class "$url")
Categories=Network;
X-CoreDesktop-WebApp=true
EOF
  update-desktop-database -q "$APPS" 2> /dev/null
  echo "Added $name to your apps."
}

remove() {
  local file
  [ -n "$1" ] || { usage >&2; return 2; }
  file="$(desktop_file "$1")"
  if ! grep -qs '^X-CoreDesktop-WebApp=true' "$file"; then
    echo "No web app named $1. These are: webapp list" >&2
    return 1
  fi
  rm -f "$file" "$ICONS/webapp-$(slug "$1").png"
  update-desktop-database -q "$APPS" 2> /dev/null
  echo "Removed $1."
}

list() {
  local file
  for file in "$APPS"/webapp-*.desktop; do
    grep -qs '^X-CoreDesktop-WebApp=true' "$file" || continue
    printf '%-24s %s\n' "$(sed -n 's/^Name=//p' "$file")" "$(sed -n 's/^Comment=//p' "$file")"
  done
}

open_app() {
  local browser
  check_url "$1" || return 1
  if browser="$(app_browser)"; then
    exec "$browser" --app="$1"
  fi
  exec xdg-open "$1"
}

case "$1" in
  add) shift; add "$@" ;;
  remove|rm) shift; remove "$@" ;;
  list|ls) list ;;
  open) shift; open_app "$@" ;;
  -h|--help) usage ;;
  *) usage >&2; exit 2 ;;
esac
