#! /usr/bin/env bash

# Adapted from https://github.com/basecamp/omarchy/tree/master?tab=readme-ov-file
SCRIPTS="${SCRIPTS:-$HOME/.local/scripts}"
THIS_FILE=${BASH_SOURCE[0]}
LOG_LABEL=$(basename "$THIS_FILE")
THIS=$(basename "$THIS_FILE")
LOG_FILE=${LOG_FILE:-"$LOG_LABEL.log"}

usage() {
  cat <<EOF

Launches a url as a web application. This script relys on the 'launch' script. This
essentially just generates the pattern and launch command to pass into that script.

USAGE:

  $ $THIS [OPTIONS] <url> [ARGS...]

OPTIONS:

  -f | --or-focus:         If a window exists matching the url's domain, focus it 
                           instead of launching new window.
  -s | --special <name>:   Launch in the special workspace name, or toggle the special 
                           workspace.
  -h | --help:             Show this help page.

NOTES:

Any extra arguments after '--' get passed directly to the browser invocation.
  
  $ launch-webapp https://example.com -- --some-random-flag-for-browser=1

Any options passed in prior to the '--' get sent to the 'launch' script, so you can pass
options that are not specifically shown here, but the ones shown would be the most commonly
used, so they are documented here.

Using the '--special' flag is useful for apps that you want to have a "summoning" like behavior. 
Upon first launch the application will be opened and the special workspace will be shown.  
Calling it again will keep the application open in the special workspace but hide the workspace.
Further calls will not open another instance of the application, but will toggle the visiblity
of the special workspace.

EOF
}

browser="brave-browser.desktop"
url=""
launch_args=()
app_args=""

while [[ $# -gt 0 ]]; do
  if [[ $1 =~ ^--special ]] || [[ $1 =~ ^-s ]]; then
    launch_args+=("$1")
    launch_args+=("$2")
    shift # Second shift get's handled below
  elif [[ $1 =~ ^--help ]] || [[ $1 =~ ^-h ]]; then
    usage && exit 0
  elif [[ -z $url ]] && [[ ! $1 =~ ^- ]]; then
    url=$1
  elif [[ $1 == "--" ]]; then
    shift
    break
  else
    launch_args+=("$1")
  fi
  shift
done

# Strips url down to just the domain, so that we can match window classes.
pattern() {
  pattern=${url/#https:\/\//}
  pattern=${pattern/#http:\/\//}
  pattern=${pattern%%/*}
  echo $pattern
}

log() {
  logging log --source "$THIS_FILE" "$@"
}

##################################################
# MAIN
##################################################

# setup logging file and label
source "$SCRIPTS/hypr/logging"
setup-logging "$LOG_FILE" "$LOG_LABEL"

if [[ -z $url ]]; then
  log --error "Must supply a url." && usage && exit 1
fi

# Any left over args after "--"
app_args="$@"

log "URL: $url"
log "Launch args: ${launch_args[@]}"
log "App args: ${app_args}"

$SCRIPTS/hypr/launch "${launch_args[@]}" "$(pattern)" \
  setsid uwsm app -- $(sed -n 's/^Exec=\([^ ]*\).*/\1/p' {~/.local,~/.nix-profile,/usr}/share/applications/$browser 2>/dev/null | head -1) --app="$url" "$app_args"
