#!/bin/bash
# Given a pristine file's SHA1, which is missing from the PRISTINE table but
# referenced from the NODES table, download it into the pristine store and
# insert a PRISTINE table row.

SHA1="$1"

set -e

PRISTINE=.svn/pristine/${SHA1:0:2}/$SHA1.svn-base
echo "In NODES table:"
svnsqlite3 'select * from nodes where checksum="$sha1$'$SHA1'"'
RRP=$(svnsqlite3 'select repos_path from nodes where checksum="$sha1$'$SHA1'"')
REV=$(svnsqlite3 'select revision from nodes where checksum="$sha1$'$SHA1'"')
echo "In PRISTINE table:"
svnsqlite3 'select * from pristine where checksum="$sha1$'$SHA1'"'
if [ -e "$PRISTINE" ]; then
  echo >&2 "Pristine file already exists: $PRISTINE"
  exit 1
fi
echo "Downloading '^/$RRP@$REV'..."
svn cat "^/$RRP@$REV" > $PRISTINE
V=$(sha1sum "$PRISTINE"); V=${V:0:40}
echo "SHA1: $V"
V=$(md5sum "$PRISTINE"); MD5=${V:0:32}
echo "MD5:  $MD5"
LEN=$(stat --printf=%s "$PRISTINE")
echo "Len:  $LEN"
echo "Inserting PRISTINE table row..."
#echo svnsqlite3 'insert into pristine values ("$sha1$'$SHA1'", null, '$LEN', 1, "$md5 $'$MD5'")'
svnsqlite3 'insert into pristine values ("$sha1$'$SHA1'", null, '$LEN', 1, "$md5 $'$MD5'")'
svnsqlite3 'select * from pristine where checksum="$sha1$'$SHA1'"'
