#!/usr/bin/perl

# Copyright (C) 2010 Thorsten Kukuk
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# in Version 2 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301, USA.


=head1 NAME

geo-fetchgpx - download GPX file from geocaching.com

=head1 SYNOPSIS

geo-fetchgpx [options] <GCxxx> ...

=head1 DESCRIPTION

Download gpx files from geocaching.com

=head1 OPTIONS

  -d|--dir <dir>            Store files in <dir> (default local directory)
  -f|--fixgpx               Run geo-fixgpx with the downloaded GPX file
  -p|--password <password>  Password for geocaching.com
  -u|--user <account>       geocaching.com account
  --logout                  Logout after download of GPX file
  -q|--quiet                Don't print any status messages
  --dump-config             Write current options as default to config
  --version                 Print version and exit
  --usage                   Print usage
  --man                     Display manual page
  -h|-?                     Help

=cut

use strict;
use warnings;
use Pod::Usage;
use File::Path;
use Config::IniFiles;
use GEO::GC;

#
# process command line arguments
#
use Getopt::Long;
my $help = 0;
my $man = 0;
my $version = 0;
my $usage = 0;
my $dir;
my $dump_config = 0;
my $homedir = '';

if ($ENV{HOME}) {
  $homedir = $ENV{HOME};
} elsif ($ENV{HOMEDRIVE} && $ENV{HOMEPATH}) {
  $homedir = $ENV{HOMEDRIVE}."/".$ENV{HOMEPATH};
}
my $cfgname = $homedir."/.geo-tools.cfg";

if (!-r $cfgname) {
  my $cfg = new Config::IniFiles(-default => "Global",
                                 -nocase => 1);
  $cfg->AddSection("geo-fetchgpx");
  $cfg->newval("geo-fetchgpx", "save_cookies", 1);
  $cfg->WriteConfig($cfgname);
}

my $cfg = new Config::IniFiles(-file => $cfgname,
                               -default => "Global");
if (!$cfg->SectionExists("geo-fetchgpx")) {
  $cfg->AddSection("geo-fetchgpx");
  $cfg->newval("geo-fetchgpx", "save_cookies", 1);
  $cfg->WriteConfig($cfgname);
}
my $save_cookies = $cfg->val("geo-fetchgpx", "save_cookies", 1);
my $sleep = $cfg->val("geo-fetchgpx", "sleep", 6);
my $gcuser = $cfg->val("geo-fetchgpx", "gcuser");
my $gcpassword = $cfg->val("geo-fetchgpx", "gcpassword");
my $quiet = $cfg->val("geo-fetchgpx", "quiet");
my $fixgpx = $cfg->val("geo-fetchgpx", "fixgpx", 0);
my $logout = $cfg->val("geo-fetchgpx", "logout", 0);

GetOptions('d|dir=s' => \$dir,
	   'u|user=s' => \$gcuser,
	   'f:1' => \$fixgpx,
	   'fixgpx!' => \$fixgpx,
	   'p|password=s' => \$gcpassword,
	   'logout!' => \$logout,
	   'dump-config' => \$dump_config,
	   'q:1' => \$quiet,
	   'quiet!' => \$quiet,
	   'version' => \$version,
	   'man' => \$man,
	   'usage' => \$usage,
	   'help|h|?' => \$help) or pod2usage(2);
pod2usage(0) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
pod2usage(-exitstatus => 0, -verbose => 0) if $usage;

if ($version) {
  print "geo-fetchgpx (geo-tools) 1.23\n";
  exit;
}

if ($dump_config) {
  WriteConfig();
  exit 0;
}

my @GCCODES;
if ($#ARGV >= 0) {
   @GCCODES = (@ARGV);
}
else {
  pod2usage(-exitstatus => 1, -verbose => 0);
}

mkpath($dir, {verbose => 1, mode => 0755}) if ($dir);

my $gc = new GEO::GC(save_cookies => $save_cookies, sleep => $sleep,
		     quiet => $quiet,
		     account => $gcuser, password => $gcpassword);

foreach my $GCCODE (@GCCODES) {
  my $filename = $GCCODE.".gpx";
  $filename = $dir . "/" . $filename if ($dir);

  $gc->fetchgpx($GCCODE, $filename);
  if ($fixgpx) {
    print "Running geo-fixgpx ...\n" unless $quiet;
    system("geo-fixgpx", "--no-warn", "--no-remove-archived",
	   "--no-remove-disabled", "--no-date", "--quiet", $filename);
    if ($? != 0) {
      die "Running geo-fixgpx on $filename failed!\n";
    } else {
      my $fixgpx_filename = $filename;
      $fixgpx_filename =~ s/.gpx$/-mod.gpx/;
      rename ($fixgpx_filename, $filename);
    }
  }
  print "Download was successful: $filename\n" unless $quiet;
}

if ($logout) {
  $gc->random_sleep($gc->sleep);
  $gc->logout();
}

exit;

sub WriteConfig
{
  $cfg->newval("geo-fetchgpx", "save_cookies", $save_cookies);
  $cfg->newval("geo-fetchgpx", "quiet", $quiet);
  $cfg->newval("geo-fetchgpx", "fixgpx", $fixgpx);
  $cfg->newval("Global", "gcuser", $gcuser);
  $cfg->newval("Global", "gcpassword", $gcpassword);
  $cfg->newval("Global", "logout", $logout);
  $cfg->newval("Global", "sleep", $sleep);
  $cfg->WriteConfig($cfgname);
}
