#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
  if 0;    # not running under some shell

use 5.008005;
use strict;
use warnings;

BEGIN {
    # use local::lib if available
    my ($HOME) = $ENV{HOME} =~ /^([\w\/]+)$/;
    if ( $HOME and -d "$HOME/perl5/lib/perl5" ) {
        eval("use lib '$HOME/perl5/lib/perl5'");
    }
}

use File::Which  ();
use Getopt::Long ();
use Carp         ();
use Pod::Usage   ();

$| = 1;

if ( $ENV{PADRE_DIE} ) {
    $SIG{__DIE__} = sub { print STDERR Carp::longmess "\nDIE: @_\n" . ( "-" x 80 ) . "\n" };
}

# Must run using wxPerl on OS X.
if ( $^O eq 'darwin' and $^X !~ m{/wxPerl\.app/} ) {
    _spawn_wx_perl();
    exit(0);
}

# Handle special command line cases early, because options like --home
# MUST be processed before the Padre.pm library is loaded.

my $USAGE   = '';
my $VERSION = '';
my $HOME    = undef;
my $SESSION = undef;
my $DESKTOP = undef;

my $getopt = Getopt::Long::GetOptions(
    'help'      => \$USAGE,
    'home=s'    => \$HOME,
    'session=s' => \$SESSION,
    'desktop'   => \$DESKTOP,
    'version'   => \$VERSION,
);

if ( $USAGE or !$getopt ) {
    Pod::Usage::pod2usage(1);
}

if ( defined $HOME ) {
    $ENV{PADRE_HOME} = $HOME;
}

require threads;
require threads::shared;

$ENV{PADRE_PAR_PATH} = $ENV{PAR_TEMP} || '';

my %opts = (
    files   => \@ARGV,
    session => $SESSION,
);

require Padre;

if ($VERSION) {
    _print_version();
    exit(0);
}
elsif ($DESKTOP) {
    _desktop_integration();
    exit(1);
}

my $app = Padre->new(%opts);

if ( !$app ) {

    # Single instance worked correctly
    exit(0);
}

# Start the application
$app->run;

sub _print_version {
    my $msg = "Perl Application Development and Refactoring Environment $Padre::VERSION\n";
    if ( $^O eq 'MSWin32' and $^X =~ /wperl\.exe/ ) {

        # Under wperl, there is no console so we will use
        # a message box
        require Padre::Wx;
        Wx::MessageBox( $msg, Wx::gettext("Version"), Wx::wxOK(), );
    }
    else {
        print $msg;
    }
}

sub _desktop_integration {
    if ( $^O eq 'MSWin32' ) {

        # Integrate with registry via regedit...
        # VBScript and registry on vista = Does not work!
        my ( $reg, $regfile ) = File::Temp::tempfile( SUFFIX => '.reg' );
        print $reg <<'REG';
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\Edit with Padre]

[HKEY_CLASSES_ROOT\*\shell\Edit with Padre\Command]
@="c:\\strawberry\\perl\\bin\\padre.exe \"%1\""
REG
        close $reg;

        # Create Padre's Desktop Shortcut
        require File::Temp;
        my ( $vbs, $vbsfile ) = File::Temp::tempfile( SUFFIX => '.vbs' );
        print $vbs <<'CODE';
' Create a Padre shortcut on the current user's desktop 
Set shell = CreateObject("WScript.Shell")
desktop = shell.SpecialFolders("Desktop")
Set shortcut = shell.CreateShortcut(desktop & "\Padre.lnk")
shortcut.Description = "Padre - The Perl IDE"
shortcut.TargetPath = "C:\strawberry\perl\bin\padre.exe"
shortcut.WorkingDirectory = "c:\strawberry\perl\bin"
shortcut.Save
MsgBox "Padre has created a shortcut on your desktop", vbOKOnly Or vbInformation, "Information"
CODE

        print $vbs <<"CODE";
' Now adding "Edit with Padre" to shell context menu
shell.Run("regedit.exe /S ""$regfile"""), 1, true
MsgBox """Edit with Padre"" has been added to your right click menu", vbOKOnly Or vbInformation, "Confirmation"
CODE
        close $vbs;
        system(qq{wscript "$vbsfile"});

    }
    elsif ( ( $^O =~ /linux|bsd/i ) ) {

        # Create Padre.desktop launcher on KDE/gnome
        my $filename = "$ENV{HOME}/Desktop/Padre.desktop";
        open my $fh, ">", $filename
          or die "Cannot create $filename: $!\n";
        require Padre::Util;
        my $logo = Padre::Util::sharedir('icons/padre/64x64/logo.png');
        print $fh <<"DESKTOP";
[Desktop Entry]
Name=Padre
Comment=Padre - The Perl IDE
Exec=/usr/local/bin/padre
Icon=$logo
Terminal=false
Type=Application
Categories=Development;Utility;
MimeType=text/plain;application/x-perl;application/x-perl6;
DESKTOP
        close $fh;
    }
    else {
        warn "--desktop not implemented for " . $^O . "\n";
    }
}

sub _spawn_wx_perl {
    my $perl = scalar File::Which::which('wxPerl');
    chomp($perl);

    if ( -e $perl ) {
        warn "spawning 'wxPerl' interpreter for OS X\n";
        system( $perl, '-S', $0, @ARGV );
    }
    else {
        warn "padre cannot find wxPerl executable (which it requires on OS X)\n";
    }

    exit 0;
}

__END__

=head1 NAME

padre - the perl IDE

=head1 SYNOPSIS

    padre [options] [filenames]

=head2 OPTIONS

=over

=item --home=dir

Forces Padre's "home" directory to a specific location

=item --help

Shows this help message

=item --session=name

Open given session during Padre startup

=item --version

Prints Padre version and quits

=back

=head1 COPYRIGHT

Copyright 2008-2009 The Padre development team as listed in Padre.pm.

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl 5 itself.
