#!/bin/sh
# Mac completion helper. In Terminal, with the approved capture folder:
#   sh ~/Downloads/Mark-Finished.sh ~/Documents/MemoryLab
# A capture is marked finished (NAME.ready.json beside it) once it has been quiet for ten
# seconds and lsof shows no program holding it open, the Mac counterpart of Mark-Finished.ps1.
# No network access, credentials, installation, admin rights or Gatekeeper changes; it uses
# only the perl and lsof that ship with macOS (10.12 onward). Running it with sh needs no
# execute permission. Qualification on the actual library Mac remains required.
if ! command -v perl >/dev/null 2>&1 || [ ! -x /usr/sbin/lsof ]; then
  echo 'This Mac lacks perl or lsof. Use "Add completed files" on the uploader page instead.' >&2
  exit 1
fi
exec perl -x "$0" "$@"
#!perl
use strict;
use warnings;
use Cwd qw(abs_path);
use File::Find qw(find);
use Time::HiRes qw(stat time sleep);

my ($folder, $quiet) = @ARGV;
$quiet = 10 unless defined $quiet;
die "Usage: sh Mark-Finished.sh CAPTURE_FOLDER [QUIET_SECONDS]\n" unless defined $folder && -d $folder;
# The page compares modification times to the second; marks must follow at least that long a pause.
die "QUIET_SECONDS must be a whole number of at least 2\n" unless $quiet =~ /^\d+$/ && $quiet >= 2;
my $root = abs_path($folder);
my %media = map { $_ => 1 } qw(tif tiff jpg jpeg png heic heif dng wav flac mp3 m4a mp4 mkv mov avi dv webm aiff aif);
$| = 1;

# "dev:inode" of each named file some process has open; undef when lsof could not run.
sub open_files {
    my %open;
    my @files = @_;
    while (my @batch = splice(@files, 0, 200)) {
        open(my $pipe, '-|', '/usr/sbin/lsof', '-w', '-F', 'Di', '--', @batch) or return undef;
        my $dev;
        while (my $line = <$pipe>) {
            if ($line =~ /^[pf]/) { $dev = undef }
            elsif ($line =~ /^D(0x[0-9a-f]+)$/i) { $dev = hex $1 }
            elsif ($line =~ /^i(\d+)$/ && defined $dev) { $open{"$dev:$1"} = 1 }
        }
        close $pipe;
        # lsof exits 1 when none of the files is open; anything else means it did not work.
        return undef if $? >> 8 > 1 || $? & 127;
    }
    return \%open;
}

# Prove lsof can see an open file here before trusting it to say a capture is closed.
my $probe = "$root/.mark-finished-check-$$";
open(my $hold, '>', $probe) or die "Cannot write completion markers in $root: $!\n";
my @probe = stat $probe;
my $seen = open_files($probe);
close $hold;
unlink $probe;
die "lsof could not see an open file in $root, so finished captures cannot be told from active ones.\n"
  . "Use \"Add completed files\" on the uploader page instead.\n"
  unless $seen && $seen->{"$probe[0]:$probe[1]"};

print "Watching $root for completed captures. Leave this window open; press Control-C to stop.\n";
while (1) {
    my @candidates;
    find({no_chdir => 1, wanted => sub {
        my $path = $File::Find::name;
        my ($name) = $path =~ m{([^/]+)\z};
        if ($name =~ /^\./ && $path ne $root) {
            # Hidden folders, and macOS ._ resource files on exFAT/FAT drives.
            $File::Find::prune = 1 if -d $path;
            return;
        }
        return if -l $path || !-f _ || $name !~ /\.([^.]+)\z/ || !$media{lc $1};
        my @st = stat $path or return;
        my ($size, $mtime) = @st[7, 9];
        return if !$size || time - $mtime < $quiet;
        my $modified = int($mtime * 1000);
        if (open(my $in, '<', "$path.ready.json")) {
            local $/;
            my $old = <$in>;
            close $in;
            return if defined $old && $old =~ /"size":$size\b/ && $old =~ /"modified":$modified\b/;
        }
        push @candidates, [$path, "$st[0]:$st[1]", $size, $modified];
    }}, $root);
    if (@candidates) {
        my $open = open_files(map { $_->[0] } @candidates);
        if (!$open) {
            print "lsof did not answer; nothing marked this pass.\n";
        } else {
            for my $c (@candidates) {
                my ($path, $id, $size, $modified) = @$c;
                next if $open->{$id};
                # A writer that touched the file while lsof ran gets another quiet period.
                my @st = stat $path or next;
                next unless "$st[0]:$st[1]" eq $id && $st[7] == $size && int($st[9] * 1000) == $modified;
                my $marker = "$path.ready.json";
                open(my $out, '>', "$marker.tmp") or next;
                print $out "{\"size\":$size,\"modified\":$modified}";
                close $out or next;
                rename "$marker.tmp", $marker or next;
                print 'Marked finished: ', substr($path, length($root) + 1), "\n";
            }
        }
    }
    sleep 3;
}
