#!/bin/bash

umask 0077
# new profile directory
npdir=~/.config/fbpanel
# old profile directory
opdir=~/.fbpanel
# system profile directory
spdir=@datadir@
# 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

    local browser terminal filer
    for browser in x-www-browser firefox opera; do
        if which $browser 2> /dev/null > /dev/null; then
            opt="$opt -e s/x-www-browser/$browser/"
            break
        fi
    done
    for terminal in x-terminal urxvt gnome-terminal; do
        if which $terminal 2> /dev/null > /dev/null; then
            opt="$opt -e s/x-terminal/$terminal/"
            break
        fi
    done
    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

