#!/bin/sh

# This file is covered by the GNU General Public License,
# which should be included with libshell as the file LICENSE.
# All copyright information are listed in the COPYING.

# Copyright (C) 2012 Andrew V. Stepanov <stanv@altlinux.org>

#
# Open URL/path using xdg-open
# http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html
#

# Use libshell
. shell-config
. shell-quote
. shell-var
export verbose=1

if [ -z "${__included_rd_url-}" ]; then
__included_rd_url=1

run_url() {
    
    local profile_file="$1" && shift
    local client="/usr/bin/xdg-open"

    if ! [ -x "$client" ]; then
        verbose "Can't find $client"
        return 1
    fi

    # Create sub-shell to save virgin environment
    (
    local OPTIONS=
    local msg=
    local ret=

    # Include profile
    . "$profile_file"
  
    # Check connection method
    if [ -z "$URLPATH" ]; then
        verbose "Bad profile: no URLPATH specified"
        return 1
    fi

    # Run client
    "$client" "$URLPATH"
    ret=$?

    return $ret
    )

    return $?
}

fi #__included_rd_url

PROFILE_URL=
PROFILES_PATH="/etc/alterator-rd"

#
# ENTER POINT
#

if [ "${#*}" -ne 1 ]; then
    echo "Use: $PROG <PROFILE>"
    exit 1
fi

for i in "$1" "$PROFILES_PATH/$1"; do
    if [ -r "$i" -a -f "$i" ]; then
        PROFILE_URL="$i"
        verbose "Found profile: $PROFILE_URL"
        break
    fi
done

if [ -z "$PROFILE_URL" ]; then
    fatal "Can't find profile: $1"
fi

run_url "$PROFILE_URL"
ret=$?

verbose "Client exited with $ret"
