#!/usr/bin/env bash
{{!
  Based on https://github.com/chriskempson/base16-builder/blob/master/templates/mate-terminal/dark.sh.erb
}}
# Base16 {{scheme-name}} - Mate Terminal color scheme install script
# {{scheme-author}}

[[ -z "$PROFILE_NAME" ]] && PROFILE_NAME="Base 16 {{scheme-name}}"
[[ -z "$PROFILE_SLUG" ]] && PROFILE_SLUG="base-16-{{scheme-slug}}"
[[ -z "$DCONFTOOL" ]] && DCONFTOOL=dconf
[[ -z "$BASE_KEY" ]] && BASE_KEY=/org/mate/terminal

PROFILE_KEY="$BASE_KEY/profiles/$PROFILE_SLUG"
DEFAULT_SLUG=$("$DCONFTOOL" read "$BASE_KEY/global/default-profile" | tr -d \')
DEFAULT_KEY="$BASE_KEY/profiles/$DEFAULT_SLUG"

dcopy() {
  local from="$1"; shift
  local to="$1"; shift

  "$DCONFTOOL" dump "$from/" | "$DCONFTOOL" load "$to/"
}

dset() {
  local key="$1"; shift
  local val="$1"; shift

  "$DCONFTOOL" write "$PROFILE_KEY/$key" "$val"
}

glist_append() {
  local key="$1"; shift
  local val="$1"; shift

  local entries="$(
    {
      "$DCONFTOOL" read "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val"
      echo "'$val'"
    } | head -c-1 | tr "\n" ,
  )"

  "$DCONFTOOL" write "$key" "[$entries]"
}

if [ -n "$DEFAULT_SLUG" ]; then
  dcopy "$DEFAULT_KEY" "$PROFILE_KEY"
fi

dset visible-name "'$PROFILE_NAME'"
dset palette "'#{{base00-hex}}:#{{base08-hex}}:#{{base0B-hex}}:#{{base0A-hex}}:#{{base0D-hex}}:#{{base0E-hex}}:#{{base0C-hex}}:#{{base05-hex}}:#{{base03-hex}}:#{{base09-hex}}:#{{base01-hex}}:#{{base02-hex}}:#{{base04-hex}}:#{{base06-hex}}:#{{base0F-hex}}:#{{base07-hex}}'"
dset background-color "'#{{base00-hex}}'"
dset foreground-color "'#{{base05-hex}}'"
dset bold-color "'#{{base05-hex}}'"
dset bold-color-same-as-fg "true"
dset use-theme-colors "false"
dset use-theme-background "false"

glist_append "$BASE_KEY/global/profile-list" "$PROFILE_SLUG"

unset PROFILE_NAME
unset PROFILE_SLUG
unset DCONFTOOL
unset BASE_KEY
unset PROFILE_KEY
unset DEFAULT_SLUG
unset DEFAULT_KEY
