#!/bin/bash

# Desc: Writes keys from dconf dump
# Purpose: Applying custom dconf dump without clobbering other keys
# Usage: bkdconfwf [file]
# Note: Useful if 'dconf load [file]' wipes existing settings.

# Yell, Die, Try Three-Fingered Claw technique
# Ref/Attrib: https://stackoverflow.com/a/25515370
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

#declare -A LG_AA # Associative Array for dconf <dir/key> and <value>

# Process input file - save <dir/key> & <value> pairs to LG_AA
FILEIN="$1"
cat "$FILEIN" | while read line; do
    yell "Begin processing of:$line";
    if [[ "$line" == "" ]]; then # Check for non-blank line
	yell "Blank line detected.";
    elif [[ "$line" =~ ^"["(.*)"]"$ ]]; then # Check for bracket-enclosed string (new line group)
	yell "New line group detected at line:$line";
	# Note start of new line group
	lgNum=0
	# Extract path
        lgDir="$line";
	lgDir="${lgDir#[*}"; # See [2]
	lgDir="${lgDir%*]}"; # See [2]
	yell "Path is:$lgDir";
    elif [[ "$line" =~ (.*)"="(.*) ]]; then # Check for key=value pair
	yell "DEBUG:Key value pair detected:$line";
	# Extract key
	key="${line%%=*}"; # See [1,3]
	yell "Key extracted:$key";
	# Extract value
	value="${line#*=}"; # See [1,3]
	yell "Value extracted:$value";
	# Add <path/key>=<value> to associative array LG_AA
	#yell "DEBUG:LG_AA old:$LG_AA";
	#yell "DEBUG:lgDir:$lgDir";
	#yell "DEBUG:value:$value";
	#LG_AA["$lgDir/$key"]+="'$value' ";
	#yell "DEBUG:LG_AA new:${LG_AA[@]}";
	# Apply keyvalue pair
	try dconf write "/$lgDir/$key" "$value";
    else
	yell "ERROR:Unrecognized string detected."
    fi;
    # Increment line group counter
    ((lgNum++)) 
    yell "DEBUG:line group number:$lgNum"
    yell "Finished processing of:$line";
    yell "=============================";
done

# Ref/Attrib
# [1] How to extract substrings around specific character using parameter expansion. chepner. https://stackoverflow.com/a/15149278 https://stackoverflow.com/questions/15148796/get-string-after-character#comment43744397_15149278
# [2] How to extract string from brackets. Alex Howansky. https://stackoverflow.com/a/7209856
# [3] Advanced Bash-Scripting Guide, section 10.1 Manipulating Strings http://tldp.org/LDP/abs/html/string-manipulation.html