#!/bin/sh
MOS_XDG_TESTING="${MOS_XDG_TESTING:-0}"
MOS_XDG_TYPE="${MOS_XDG_TYPE:-}"
MOS_XDG_CONFIG_DIR=/etc/xdg/mos
MOS_XDG_DATA_DIR=/usr/share/mos
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/kf5/xdg:/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/kf5/xdg:/etc/xdg
# into XDG_CONFIG_DIRS=/home/user/.config/kdedefaults:/etc/xdg/mos:/etc/kf5/xdg:/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(){
    local tmp
    # current value
    tmp="$1"
    # /etc/xdg, /usr/share
    root1="$2"
    # /etc/kf5/xdg, /usr/share/kf5
    root2="$3"
    # /etc/xdg/mos, /usr/share/mos
    add="$4"
    case "$tmp" in
        "" )
            # https://bugzilla.altlinux.org/show_bug.cgi?id=41566
            tmp="$root2":"$root1"
        ;;
        :"$root1" )
            # not a valid value!
            tmp="$root1"
        ;;
        "$root1" )
            :
        ;;
        *"$root1" )
            :
        ;;
        * )
            # not a valid values - does not end with /etc/xdg or /usr/share
            tmp="$tmp":"$root1"
        ;;
    esac
    case "$tmp" in
        *:"$root1"/mos:* | "$root1"/mos:* )
            :
        ;;
        *:"$root2":* )
            tmp="$(echo "$tmp" | sed -e "s,:${root2}:,:${add}:${root2}:,")"
        ;;
        "$root2":* )
            tmp="$(echo "$tmp" | sed -e "s,^${root2}:,${add}:${root2}:,")"
        ;;
        *:"$root1" )
            tmp="$(echo "$tmp" | sed -e "s,:${root1},:${add}:${root1},")"
        ;;
        "$root1" )
            tmp="$(echo "$tmp" | sed -e "s,^${root1},${add}:${root1},")"
        ;;
    esac
    echo "$tmp"
}

_main(){
    _check_runability "$1"
    # $XDG_DATA_DIRS may be added
    local result_xdg_config_dirs
    result_xdg_config_dirs="$(_mk_xdg_dirs "$XDG_CONFIG_DIRS" /etc/xdg /etc/kf5/xdg "$MOS_XDG_CONFIG_DIR")"
    local result_xdg_data_dirs
    result_xdg_data_dirs="$(_mk_xdg_dirs "$XDG_DATA_DIRS" /usr/share /usr/share/kf5 "$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