#!/bin/bash

# According to XDG Base Directory Specification
# https://specifications.freedesktop.org/basedir-spec/latest/

MOS_XDG_TESTING="${MOS_XDG_TESTING:-0}"
MOS_XDG_TYPE="${MOS_XDG_TYPE:-}"

MOS_XDG_CONFIG_DIR=/etc/xdg/mostech
MOS_XDG_DATA_DIR=/usr/share/mostech

XDG_CONFIG_DIRS="${XDG_CONFIG_DIRS:-}"

_check_runability(){
    case "$1" in
        systemd ) : ;;
        profile ) : ;;
        * )
            echo 'Set $MOS_XDG_TYPE to systemd or profile!' >&2
            return 1
        ;;
    esac
}

# XXX Who is that crazy person who sets adds ~/.config/kdedefaults to
# XDG_CONFIG_DIRS=/home/user/.config/kdedefaults:/etc/xdg
# and why does he do such a strange thing?!
# Example of what we have to do:
# convert XDG_CONFIG_DIRS=/home/user/.config/kdedefaults:/etc/xdg
# into XDG_CONFIG_DIRS=/home/user/.config/kdedefaults:/etc/xdg/mostech:/etc/xdg
# I do not want to write very complex code to deal with all possible cases.
# Let's assume that current value:
# * is not a mess and is a valid value
# * does not have repeated directories (if it has, we will probably still be OK)
# $1: current value of $XDG_CONFIG_DIRS
_mk_xdg_dirs(){
    # current value
    local tmp
    tmp="$1"

    # /etc/xdg, /usr/share
    local default
    default="$2"

    # /etc/xdg/mostech, /usr/share/mostech
    local add
    add="$3"

    # The first pass - checking availability of standard paths
    case "$tmp" in
        "" | :"$default" )
            # Empty value or not valid value
            tmp="$default"
        ;;
        *"$default" | "$default" )
            :
        ;;
        * )
            # not a valid values - does not end with /etc/xdg or /usr/share
            tmp="$tmp":"$default"
        ;;
    esac

    # The second pass - append mos dirs
    case "$tmp" in
        *:"$add":* | "$add":* )
            :
        ;;
        *:"$default" | "$default" )
            tmp="$(echo "$tmp" | sed -e "s,${default},${add}:${default},")"
        ;;
    esac
    echo "$tmp"
}

_main(){
    _check_runability "$1"

    local result_xdg_config_dirs
    result_xdg_config_dirs="$(_mk_xdg_dirs "$XDG_CONFIG_DIRS" /etc/xdg "$MOS_XDG_CONFIG_DIR")"

    local result_xdg_data_dirs
    result_xdg_data_dirs="$(_mk_xdg_dirs "$XDG_DATA_DIRS" "/usr/local/share:/usr/share" "$MOS_XDG_DATA_DIR")"

    case "$1" in
        systemd )
            echo XDG_CONFIG_DIRS="$result_xdg_config_dirs"
            echo XDG_DATA_DIRS="$result_xdg_data_dirs"
        ;;
        profile )
            export XDG_CONFIG_DIRS="$result_xdg_config_dirs"
            export XDG_DATA_DIRS="$result_xdg_data_dirs"
        ;;
    esac
}

if [ "$MOS_XDG_TESTING" = 0 ]; then
    _main "$MOS_XDG_TYPE"
fi
