#!/usr/bin/perl -w
use strict;
use warnings;
use File::Basename;
use Getopt::Std;
use WWW::Shorten 'MakeAShorterLink';

my $args =  get_cli_options();
my $url = shift;
my $modded_url;

#for (sort keys %$args){ print "key => '$_' value => $args->{$_}\n";}

# show usage if no url agrument or -h
usage() unless $url;
usage() if $args->{'h'};

# masl requires a http infront of the url.
$url = 'http://' . $url unless $url =~ m!^http://!;

if (valid_args($args)) {
  if ($args->{'l'}) {
    $modded_url = lengthen($url);
  } else {
    $modded_url = shorten($url);
  }
}

#show them the fruits of our labour.
print $modded_url;
print "\n" unless $args->{'n'};

exit 0;

##################################
# functions
##################################

#simple function so i can use different modules for this.
sub get_cli_options {
  my %args;
  getopt("vDo", \%args);

  return \%args;
}

#------------------------------------#

sub usage {
  my $appname = basename $0;

print<<EOU;

$appname [-slh] URL
\t-s\tshorten a url and return the result
\t-l\tconvert a MakeAShorterLink shortened URL into its long form
\t-n\tdo not add a new line to the output
\t-h\tshow usage

If the url contains special characters then wrap it in single quotes. 
If an error is encountered then the original URL will be passed through.

EOU

#\t-f\tshow error messages on failiure

  exit 1;
}

#------------------------------------#

sub valid_args {
  my $appname = basename $0;
  my $args = shift;

  if ($args->{'l'} && $args->{'s'}) {
    die "$appname: A url can only be shortend or reverted. Not both\n";
  }
 
  return 1; 
}

#------------------------------------#

sub lengthen {
  my $url = shift;
  my $long_url  = makealongerlink($url);

  $long_url = $url unless $long_url;

  return $long_url;
}

#------------------------------------#

sub shorten {
  my $url = shift;
  my $short_url;
  my $minumum_length = 45;

  if (length($url) >= $minumum_length) {
    $short_url = makeashorterlink($url);
  } else {
    $short_url = $url;
  }

  return $short_url;
}

#------------------------------------#
