#!/bin/bash
#
# Copyright (C) 2006 Marengo Ltd (Martyn Davis)
# This code comes with ABSOLUTELY NO WARRANTY.
# It is open source and is released under the GPL; 
# please see http://www.gnu.org/licenses/gpl.txt for full details. 
#
# $Id: gps_upload.sh,v 1.2 2006/05/14 08:46:42 mcd Exp $
#

usage(){
    echo ""
    echo "Usage:   `basename $0` [options] <gpx file>"
    echo ""
    echo "Options: [ --output_port <port>   (defaults to \"usb:\" ]"
    echo "         [ --device <device name> (defaults to \"garmin\" ]"
    echo "         [ --verbose ]"
    echo ""
    echo "         All options can be abbreviated to one hyphen"
    echo "         and their first letter (e.g. -v for verbose)"
    echo ""
    exit 1
}

GPSBABEL=`which gpsbabel`
if [[ -z ${GPSBABEL} ]]; then
    echo "Cannot find the required program \"gpsbabel\" on the search path."
    echo "Please install version 1.2.8 or higher; you can find it at http://www.gspbabel.org"
    exit 3
fi

OUTPUT_PORT=usb:
DEVICE=garmin

while [[ ! -z ${1} ]]; do 
    case ${1} in
        "--output_port" | "-o" | "--o" )
            shift
            OUTPUT_PORT=${1}
            ;;
        "--device" | "-d" | "--d")
            shift
            DEVICE=${1}
            ;;
        "--verbose" | "-v" | "--v" )
            VERBOSE=Y
            ;;
        "--help"|"-help"|"--h"|"-h"|"-?")
            usage
            ;;
        *)
            if [[ ${1:0:1} == "-" ]]; then
                echo "Unknown option \"${1}\""
                exit 4
            else
                GPXFILE=${1}
            fi
    esac
    shift
done

if [[ -z ${DEVICE} || -z ${OUTPUT_PORT} || -z ${GPXFILE} ]]; then
    usage
fi

if [[ ${DEVICE:0:1} == "-" || ${OUTPUT_PORT:0:1} == "-" || ${GPXFILE:0:1} == "-" ]]; then
    usage
fi

if [[ ! -e ${GPXFILE} ]]; then
    echo "Cannot find GPX upload file \"${GPXFILE}\""
    exit 2
fi

CMD_LINE="${GPSBABEL} -r -i gpx -f ${GPXFILE} -o ${DEVICE} -F ${OUTPUT_PORT}"
if [[ ! -z ${VERBOSE} ]]; then 
    echo ${CMD_LINE}
    ${CMD_LINE}
else
    ${CMD_LINE} 2>/dev/null
fi

if [[ $? -ne 0 ]]; then
    echo "Transfer failed."
else
    echo "Done."
fi
