#!/usr/bin/perl

# Aquamacs Emacs starter
# (C) 2007, 2008, 2009, 2018, 2019 Aquamacs Project

# To-do: re-implement in C (or as a shell script)?

use strict;
use warnings;

my @args;
my @files;
my @tmpfiles;

for my $f (@ARGV) {
    if (-e $f) {
        push @files, $f;
    } elsif ($f =~ /^-/) {
        push @args, $f;
    } elsif (open my($tfh), '>', $f) {
        # Create a temp file because open doesn't work with
        # non-existing files.
        close $tfh;
        push @files, $f;
        push @tmpfiles, $f;
    } else {
        warn "$f: $!\n";
    }
}
unshift @args, '--args' if @args;

system('open', '-a', 'Aquamacs', @files, @args);

# Delay deletion of temp files because Aquamacs' drag&drop action
# requires the file to exist.
if (@tmpfiles and fork == 0) {
    sleep 3; # 3 seconds aught to be enough for Aqumacs to have
             # started and drag&drop to have been activated and small
             # enough to not be a burden.
    unlink @tmpfiles;
    exit;
}
