#!/usr/bin/env bash

# ROAD GREY
# https://github.com/jdw1996/road-grey-gnome-terminal.git
# ---------
# Gnome Terminal color scheme install script
# Based on:
#   https://github.com/denysdovhan/one-gnome-terminal
# Which is based on:
#   https://github.com/chriskempson/base16-gnome-terminal/
set -x
[[ -f "$HOME/.config/.gnome-terminal-profile-road-grey-created" ]] && exit 0
[[ -z "$PROFILE_NAME" ]] && PROFILE_NAME="Road Grey"
[[ -z "$PROFILE_SLUG" ]] && PROFILE_SLUG="road-grey"
[[ -z "$DCONF" ]] && DCONF=dconf
[[ -z "$UUIDGEN" ]] && UUIDGEN=uuidgen

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

    if [[ "$type" == "string" ]]; then
        val="'$val'"
    fi

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

# because dconf still doesn't have "append"
dlist_append() {
    local key="$1"; shift
    local val="$1"; shift

    local entries="$(
        {
            "$DCONF" read "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val"
            echo "'$val'"
        } | perl -pe 'chomp if eof' | tr "\n" ,
    )"

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

# Newest versions of gnome-terminal use dconf
if which "$DCONF" > /dev/null 2>&1; then
    [[ -z "$BASE_KEY_NEW" ]] && BASE_KEY_NEW=/org/gnome/terminal/legacy/profiles:

    if [[ -n "`$DCONF list $BASE_KEY_NEW/`" ]]; then
        if which "$UUIDGEN" > /dev/null 2>&1; then
            PROFILE_SLUG=`uuidgen`
        fi

        if [[ -n "`$DCONF read $BASE_KEY_NEW/default`" ]]; then
            DEFAULT_SLUG=`$DCONF read $BASE_KEY_NEW/default | tr -d \'`
        else
            DEFAULT_SLUG=`$DCONF list $BASE_KEY_NEW/ | grep '^:' | head -n1 | tr -d :/`
        fi

        DEFAULT_KEY="$BASE_KEY_NEW/:$DEFAULT_SLUG"
        PROFILE_KEY="$BASE_KEY_NEW/:$PROFILE_SLUG"

        # copy existing settings from default profile
        $DCONF dump "$DEFAULT_KEY/" | $DCONF load "$PROFILE_KEY/"

        # add new copy to list of profiles
        dlist_append $BASE_KEY_NEW/list "$PROFILE_SLUG"

        # update profile values with theme options
        dset visible-name "'$PROFILE_NAME'"
        dset palette "['#000000', '#bc3629', '#418240', '#a27a01', '#315bb4', '#833482', '#1880a0', '#faf9fa', '#212227', '#bc3629', '#418240', '#a27a01', '#315bb4', '#833482', '#1880a0', '#ffffff']"
        dset background-color "'#c2c4cc'"
        dset foreground-color "'#212227'"
        dset bold-color "'#212227'"
        dset bold-color-same-as-fg "true"
        dset use-theme-colors "false"
        dset use-theme-background "false"

        unset PROFILE_NAME
        unset PROFILE_SLUG
        unset PROFILE_KEY
        unset DCONF
        unset UUIDGEN
        unset DEFAULT_KEY
        unset DEFAULT_SLUG
        unset BASE_NEW_KEY
        touch "$HOME/.config/.gnome-terminal-profile-road-grey-created"
        exit 0
    fi
fi

echo "dconf not found"
exit 1