#!/usr/bin/env bash

# - See: https://gist.github.com/epiloque/8cf512c6d64641bde388
# - 
# - Changes from the original (see above url: 
# - if the yaml file contains carriage returns, the processing will fail. 
# - In this case, I made a fix on this line (currently line 14)
# -
# - fs="$(echo @|tr @ '\034')"
# -
# - so it became
# - fs="$(echo @|tr @ '\034'|tr -d '\015')"
# -
# - NOTE!
# - The indent of the yaml configuration file is "2"
# -
# - If you want your indentation to be 4 spaces instead of 2 change this line:
# -    indent = length($1)/2;
# - to be this:
# -    indent = length($1)/4;
# -

working_dir="$(dirname $(realpath $0))"

# - This file will be created. (see below..)
# -
example_yaml_config_file="${working_dir}/files/example_yaml_config.yml"

parse_yaml() {
    local prefix=$2
    local s
    local w
    local fs
    s='[[:space:]]*'
    w='[a-zA-Z0-9_]*'
    #fs="$(echo @|tr @ '\034')"
    fs="$(echo @|tr @ '\034'|tr -d '\015')"
    sed -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
        -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
    awk -F"$fs" '{
    indent = length($1)/2;
    vname[indent] = $2;
    for (i in vname) {if (i > indent) {delete vname[i]}}
        if (length($3) > 0) {
            vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
            printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
        }
    }' | sed 's/_=/+=/g'
}

cat <<EOF > "$example_yaml_config_file"
development:
  adapter: mysql2
  encoding: utf8
  database: my_database
  username: root
  password:
  apt:
    - somepackage
    - anotherpackage
EOF

eval $(parse_yaml "$example_yaml_config_file" "optional_prefix_")
#parse_yaml $example_yaml_config_file "optional_prefix"

echo ""
echo "-------------------"
echo "- Read yaml configuration file"
echo "-------------------"

echo ""
echo "$example_yaml_config_file:"
cat $example_yaml_config_file


echo -e "\nUsing with optional prefix 'optional_prefix_'"
echo "============================================="
echo -e "\t\033[32meval \$(parse_yaml \"$example_yaml_config_file\" "optional_prefix_")\033[m"
echo ""
echo -e "\t\${optional_prefix_development_adapter}: ${optional_prefix_development_adapter}"
echo -e "\t\${optional_prefix_development_apt[@]}:  ${optional_prefix_development_apt[@]}"


eval $(parse_yaml "$example_yaml_config_file" )
#parse_yaml $example_yaml_config_file "optional_prefix"

echo ""
echo -e "\nUsing without optional prefix "
echo "=============================="
echo -e "\t\033[32meval \$(parse_yaml \"$example_yaml_config_file\" )\033[m"
echo ""
echo -e "\t\${development_adapter}: ${development_adapter}"
echo -e "\t\${development_apt[@]}:  ${development_apt[@]}"

echo ""
rm "$example_yaml_config_file"
exit 0
