#!/bin/bash

# 'gpxclean.sh'
#
# A script to "clean" GPX files using gpsbabel:
#
# - extracts and merges all the tracks (-x track,merge)
# - drops any routes (-x nuketypes,routes)
#
# Arguments: Name or wildcard of the file(s) to convert.
#
# NOTES:
# - There is not much error-checking done on the arguments.
# - The resulting GPX is not really conform to std, since times
#   should be given in UTC and not in local time. However, for
#   my purpose it's more interesting to have "local" time data.
#
# -----------------------------------------------------------------
# History:
#   2007-01-28, JHa, first version.
#   2007-02-15, JHa, added comments.
#   2010-09-24, JHa, added gpxver for compatibility with gpsdings
#   2021-05-14, JHa, removes timeshift
# -----------------------------------------------------------------
# Copyright (c) 2007...2021 Joerg Hau <hau.joerg(at)gmail.com>.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# -----------------------------------------------------------------


# if script is called w/o arguments, give usage instructions
#
if (( $# != 3 )) ;  then
    echo "Syntax: ${0##*/} infile.gpx outfile.gpx \"Title of Track\""
    exit 1
fi

# -----------------------------------------------------------------
# subroutine to check for some required executables
# argument: (list of) programs to test for
# will exit with rc=1 if any program was not found
# -----------------------------------------------------------------
function checkfor()
{
for i in $*; do
    PROG=`which $i`
    if [ $? != 0 ]; then
        echo "'$i' command not found, exiting."
        exit 1
    fi
done
}

# check for some mandatory stuff
#
checkfor mv gpsbabel

# file to store some intermediate information
#
tmpfile="/tmp/$$.tmp"

# action for Ctrl-C and other nasty things ...
#
trap 'if [ -x ${tmpfile} ] ; then rm ${tmpfile}; fi; exit 1' 0 1 2 3 15

# attribute and check files
#
INFILE=$1;
OUTFILE=$2;
TITLE=$3;

if [ ! -r $INFILE ] ; then
  echo "Cannot read '$INFILE' !"
  exit 1
fi

gpsbabel -t -i gpx -f ${INFILE} \
         -x track,merge,title="${TITLE}" -x nuketypes,routes \
         -o gpx,gpxver=1.1 -c latin1 -F ${tmpfile} || "Error during conversion!"

mv -i ${tmpfile} ${OUTFILE} || echo "Error during 'mv'!"

if [ -x ${tmpfile} ] ; then rm ${tmpfile}; fi
exit 0
