#!/usr/bin/perl -w
use strict;

#  Copyright (C) 2003 Anthony de Boer
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of version 2 of the GNU General Public License as
#  published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

my $gnd = $ENV{'GALLERY'};
die "No GALLERY in environment\n" unless $gnd;
my $DB = '.data';
my $ODB = $gnd . '/.data';
my $thumbprefix = '.t_';
my %wanted;
my $tc = 0;

for my $thing (@ARGV) {
	$tc = 0, last unless $thing =~ /^[\w\d\-]+$/ && $thing ne '_';
	$wanted{$thing} = 1;
	$tc++;
	}
die "Usage: $0 pageid(s)\n" unless $tc;

my $HERE = `pwd`;
chomp $HERE;

my $relhere = $HERE;
my $relgal = $gnd;
$relgal =~ s/\/$//;
$relhere =~ s/\/$//;
while(1) {
	last unless $relhere =~ /^([^\/]*\/)/;
	my $fc = $1;
	last unless $relgal =~ /^([^\/]*\/)/;
	last unless $fc eq $1;
	my $fl = length($fc);
	$relhere = substr($relhere, $fl);
	$relgal = substr($relgal, $fl);
	}
$relhere .= '/';
while($relhere =~ s/^[^\/]*\///) {
	$relgal = '../' . $relgal;
	}
print STDERR "Gallery relative path $relgal\n";

my %db;
open(DB, $ODB) || die "Cannot read $ODB: $!\n";
$/ = '';
while(<DB>) {
	my ($pg, $id, $rest) = split(/\s+/, $_, 3);
	next if $pg eq 'unsorted' && $id =~ /^\d+$/;
	$rest =~ s/\n+$//;
	die "DB entry $pg $id defined again!\n" if $db{"$pg $id"};
	$db{"$pg $id"} = $rest;
	}
close(DB);

my %otab;
my @lnf;
for my $k (sort (keys %db)) {
	next unless $k =~ /^([\w\d\-]+)\s/ && $wanted{$1};
	$otab{$k} = $db{$k};
	next unless $k =~ /\s\d+$/;
	for my $j ($db{$k}, $thumbprefix . $db{$k}) {
		my $k2 = '_ ' . $j;
		if (defined($db{$k2})) {
			$otab{$k2} = $db{$k2};
			push(@lnf, $j);
			}
		else {
			print "$k2 not found\n";
			}
		}
	}

if (open(DC, "$DB")) {
	while(<DC>) {
		my ($pg, $id, $rest) = split(/\s+/, $_, 3);
		delete ($otab{"$pg $id"});
		}
	close(DC);
	}

my $perr;
open(DO, ">>$DB") || die "Cannot append to $DB: $!\n";
for my $k (sort (keys %otab)) {
	$perr = 1 unless print DO "$k $otab{$k}\n\n";
	}
die "Cannot print $DB: $!\n" if $perr;
die "Error closing $DB: $!\n" unless close(DO);

for my $f (@lnf) {
	my $was = readlink($f);
	my $op = $relgal . '/' . $f;
	if (defined($was)) {
		print STDERR "$f exists -> $was should be $op\n" unless $was eq $op;
		next;
		}
	symlink ($op, $f) || warn "cannot symlink $op to $f: $!\n";
	}
