#!/bin/bash

action=$1
shift

function usage(){
  echo "  Open activeCollab URL:"
  echo "    ac ITEM#"
  echo "      Searches for a project and/or ticket number in the todo line and launches a browser."
  echo ""
  exit
}

[ "$action" = "usage" ] && usage

if ! [[ "$1" =~ ^[0-9]+$ ]]; then
    echo "Error! Usage:"
    usage
fi

URL=$(sed "$1!d" "$TODO_FILE"|grep -E -o "([a-z]*)ac:[^ ]+")
if [ "$URL" = "" ]; then
    LINE=$(sed "$1!d" "$TODO_FILE")
    if [ "$LINE" = "" ]; then
        echo "Error, no item #$1 found!"
    else
        echo "Error, no activeCollab URL seen in item #$1!"
        echo "$LINE"
    fi
    exit 1
fi

if [ "$AC_URL" = "" ]; then
    echo "Error, please make sure your AC_URL variable is defined in tasks.cfg!"
    exit 1
fi

URL=$(echo $URL | cut -d: -f2-)
PROJECT=$(echo $URL | awk -F / '{ print $1 }')
TICKET=$(echo $URL | awk -F / '{ print $2 }')

URL="$AC_URL/projects/$PROJECT/tickets/$TICKET"

# Trying to be smart...
# on Debian alike:
if $(which x-www-browser >/dev/null 2>&1); then
    exec x-www-browser "$URL"
# with freedesktop.org utils:
elif $(which xdg-open >/dev/null 2>&1); then
    exec xdg-open "$URL"
# if you have git:
elif [ -x /usr/lib/git-core/git-web--browse ]; then
    cd /usr/lib/git-core && ./git-web--browse "$URL"
# last resort, a la mano...
elif $(which firefox >/dev/null 2>&1); then
    exec firefox "$URL"
elif $(which konqueror >/dev/null 2>&1); then
    exec konqueror "$URL"
elif $(which nautilus >/dev/null 2>&1); then
    exec nautilus "$URL"
# Windowsien?
elif [ -x "/cygdrive/c/Program Files/Mozilla Firefox/firefox.exe" ]; then
    exec "/cygdrive/c/Program Files/Mozilla Firefox/firefox.exe" "$URL"
# OS X?
elif [ -x "/usr/bin/open" ]; then
    exec "/usr/bin/open" "$URL"
else
    echo "Sorry I'm giving up, cannot find your browser :-("
    echo "Under cygwin, consider creating a shortcut in the path, like"
    echo "ln -s \"/cygdrive/c/Program Files/Mozilla Firefox/firefox.exe\" /usr/local/bin/firefox"
fi