#!/bin/bash

umask 0077
# new profile directory
npdir=~/.config/fbpanel
# old profile directory
opdir=~/.fbpanel
# system profile directory
spdir=%%datadir%%/fbpanel
# if profile name was not set, use  'default'
profile=${1:-default}


# if profile already exists do nothing
if [ -w "$npdir/$profile" ]; then
    echo "Profile '$profile' already exists."
    echo "$npdir/$profile"
    exit 0
fi

# create profile
echo "Creating profile '$profile' at $npdir/$profile"
mkdir -p "$npdir"
touch "$npdir/$profile" || exit 1

# if personal profile with same name exists, use it
w="$w###############################################\n"
w="$w# This configuration file is not used anymore.\n"
w="$w# Now, all profiles are stored at\n#   $npdir.\n"
w="$w# Edit them instead !!! \n"
w="$w###############################################\n\n"

if [ -r "$opdir/$profile" ]; then
    cp -f "$opdir/$profile" "$npdir/$profile"
    echo "Using old $opdir/$profile as template"
    echo -e "$w" > "/tmp/$$-$profile"
    cat "$opdir/$profile" >> "/tmp/$$-$profile"
    mv "/tmp/$$-$profile" "$opdir/$profile"
    exit 0
fi

# Creates new profile using system profile as template
# $1 - system profile name
# $2 - destination profile name
function take_system_profile ()
{
    [ -r "$spdir/$1" ] || return 1

    # Don't override this and use Debian Alternatives system (See #585577). 
    opt="$opt -e s/x-www-browser/x-www-browser/"
    opt="$opt -e s/x-terminal/x-terminal-emulator/"

    local filer
    for filer in x-file-manager thunar pcmanfm rox; do
        if which $filer 2> /dev/null > /dev/null; then
            opt="$opt -e s/x-file-manager/$filer/"
            break
        fi
    done
    sed $opt < "$spdir/$1" > "$npdir/$2"
    echo "Using $spdir/$1 as template"
}

take_system_profile $profile $profile || take_system_profile default $profile

