#!/bin/sh

# Enable font-size, tabbedex and matcher extensions.
awk -v DATE="$(date -Ins)" '
# Append new extensions to existing resource.
/^URxvt.perl-ext-common:/ {
  na = split($0, a, /[: \t]+/)
  resource = a[1]
  # explode value
  ne = split(a[na], e, /,/)
  for(i = 1; i <= ne; i++) seen[e[i]] = 1;
  # add new extensions
  if(!seen[x = "font-size"]) e[++ne] = x;
  if(!seen[x = "tabbedex"])  e[++ne] = "-tabbed,"x;
  if(!seen[x = "matcher"])   e[++ne] = x;
  # implode new value
  extensions = e[1]
  for(i = 2; i <= ne; i++) extensions = extensions","e[i]
  extensions = resource": "extensions
}
END {
  # Assign new extensions to non-existent resource.
  if("" == extensions) {
    extensions = "URxvt.perl-ext-common: default,font-size,-tabbed,tabbedex,matcher"
  }
  section ="\n"\
"!Begin by package rxvt-unicode_perl-9.22-x86_64-1 {{{\n"\
"! Automatically added on "DATE"\n"\
"! Locations of perl extensions: /usr/local/lib64/urxvt/perl  ~/.urxvt/ext\n"\
"! Key mappings: Use   xev -event keyboard   to identify key names (letter case matters!)\n"\
"! Note: URxvt ISO 14755 mode preempts keysym modifier combination Shift+Control.\n"\
"!\n"\
"! Font Size extension: Font size changes apply to new windows not to new tabs; :reset applies to the current tab.\n"\
"URxvt.keysym.C-Up:    font-size:increase\n"\
"URxvt.keysym.C-Down:  font-size:decrease\n"\
"URxvt.keysym.C-Prior: font-size:incglobal\n"\
"URxvt.keysym.C-Next:  font-size:decglobal\n"\
"URxvt.keysym.C-equal: font-size:reset\n"\
"URxvt.keysym.C-slash: font-size:show\n"\
"!\n"\
"! Tabbedex extension. Default key bindings S-{Down/Up/Left/Right}, C-{Left,Right}, M-{F1..F12}\n"\
"URxvt.tabbed.tabbedex-rs-prefix: tabbedex\n"\
"!\n"\
"! Matcher extension: mouse middle button\n"\
"URxvt.matcher.button:   2\n"\
"URxvt.matcher.launcher: defaultbrowser\n"\
"! Enter url selection mode. Default key sub-bindings {Up/Down/Home/End/Escape/Enter/y(ank)}\n"\
"URxvt.keysym.M-C-u:     matcher:select\n"\
extensions"\n"\
"!End rxvt-unicode_perl-9.22-x86_64-1 }}}"
  print section >> FILENAME
  print section
}' "$HOME/.Xresources" | xrdb -merge -quiet
