#
# make sure persist really writes where its supposed to.
#
use strict;
use warnings;
use Test::More;
use File::Spec ();
use File::Temp ();
use Config;

use vars qw(@OPTS $TMPDIR $STATEFILE);

# Win32 cant unlink open files and UUID keeps the state file open,
# so we have to run tests in another process so UUID closes in child,
# thus allowing File::Temp to cleanup in parent.

BEGIN {
    if (!@ARGV) {
        my $perl = $Config{perlpath};
        if ($^O ne 'VMS') {
            $perl .= $Config{_exe}
                unless $perl =~ m/$Config{_exe}/i;
        }

        my $td = File::Temp->newdir('asserttestXXXXXXXX',
            DIR => File::Spec->curdir(), CLEANUP => 1);
        $TMPDIR = $td->dirname;
        my $tf = File::Temp->new(TEMPLATE => 'stateXXXXXXXX',
            SUFFIX => '.txt', DIR => $TMPDIR, UNLINK => 1);
        $STATEFILE = $tf->filename;

        my $bliblib  = File::Spec->catdir(qw(blib lib));
        my $blibarch = File::Spec->catdir(qw(blib arch));

        $perl .= qq( -I$bliblib -I$blibarch $0 "$TMPDIR" "$STATEFILE");

        if (system($perl) != 0) {
            if ($? == -1) {
                note "child failed to execute: $!\n";
                exit -1;
            }
            elsif ($? & 127) {
                note sprintf("child died with signal %d, %s coredump\n",
                    ($? & 127),  ($? & 128) ? 'with' : 'without');
                exit $? >> 8;
            }
            else {
                note sprintf("child exited with value %d\n", $? >> 8);
                exit $? >> 8;
            }
        }
        exit 0;
    }

    $TMPDIR    = shift @ARGV;
    $STATEFILE = shift @ARGV;

    @OPTS = ":persist=$STATEFILE";
}

use UUID @OPTS;

ok 1, 'loaded';

ok -d $TMPDIR,    'tempdir exists';
ok -f $STATEFILE, 'state file exists';

my $uu = UUID::uuid1();
ok 1,                          'got something';
is length($uu), 36,            'looks like uuid';
like $uu, qr/^[-0-9a-f]{36}$/, 'smells like uuid';

# does the content look reasonable?
{
    open my $fh, '<', $STATEFILE or die "open: $STATEFILE: $!";
    my $state = <$fh>;
    is length($state), 56, 'content length';
    like $state, qr/clock:\s+[0-9a-f]{4}\s/,             'clock field';
    like $state, qr/tv:\s+[0-9a-f]{16}\s+[0-9a-f]{8}\s/, 'tv field';
    like $state, qr/adj:\s+[0-9a-f]{8}/,                 'adj field';
}

done_testing;
