#!/bin/bash
#
# (C)opyright 2017-07-13 Dirk Holtwick, holtwick.it. All rights reserved.
# https://www.receipts-app.com
#
# Inspired by: 
# https://stackoverflow.com/questions/18259692/how-to-recover-a-corrupt-sqlite3-database

if [ -z "$1" ]; then 
    echo "Usage: $0 <ReceiptsLibrary>.receipts"; 
	echo 
	echo "PLEASE CREATE A BACKUP BEFORE RUNNING THIS SCRIPT!"
    exit 1;
fi

cd "$1"
echo "1. Dump SQLite Error Messages"
sqlite3 Database.sqlite "PRAGMA integrity_check"

DATE=`date +%Y%m%d-%H%M%S`
BACKUP="Backup-Repair-$DATE"

echo
echo "2. Create Local Backup"
mkdir -p $BACKUP
cp -vfa Database.* $BACKUP
rm -f Database.*

echo
echo "3. Repair Database (Please wait, may take a while)"
sqlite3 $BACKUP/Database.sqlite ".dump" | sqlite3 Database.sqlite 

echo
echo "Done"
