#!/bin/bash

# This script tries to recover damaged files using ddrescue
# Created: 2017.03.05 19:41
# Author: Kārlis Kalviškis <eko@lanet.lv>
# License: GPLv3

# For translation
export TEXTDOMAIN="karlo-scripts"
. gettext.sh

Usage (){
	echo
	echo `eval_gettext 'Unknown parameter'`!
	echo
	echo `eval_gettext 'Usage'`:
	echo "${PROG}_files" `eval_gettext 'source_directory'` `eval_gettext 'destination_directory'`
	echo 
}

if [ $# -eq 3 ]; then
	PROG="$1"; shift
	if [ ! "$1" -o  ! "$2" ]; then
		Usage; exit
	fi
else
	PROG="ddrescue"
fi

echo
echo `eval_gettext 'This script tries to recover damaged files using'` $PROG.
type -P $PROG &>/dev/null || { echo  "`eval_gettext 'Command'` '$PROG' `eval_gettext 'is missing'`"; exit 10; }

if [ $# -ne 2 ]; then
	Usage
	exit 1
fi  

WhereAmI=$PWD
WhereAreFiles=$1
SafePlace=$2
if [ ${SafePlace:0:1} != '/' ]; then
	SafePlace=$WhereAmI/$SafePlace
fi

if [ ! -d $WhereAreFiles ]; then
	echo -e "\033[1;95m"
	echo "`eval_gettext 'Source directory'` '$WhereAreFiles' `eval_gettext 'does not exists'`!"
	echo -e "\033[0;0m"
	exit 2
fi

echo "`eval_gettext 'Sorce'`: $WhereAreFiles"
echo "`eval_gettext 'Destination'`: $SafePlace"
if [ -d $SafePlace ]; then
	echo -e "\033[1;95m"
	echo "`eval_gettext 'Destination already exists'`!!!"
	echo "`eval_gettext 'Files will be overwritten'`!"
	echo -e "\033[0;0m"
fi
while true; do
    read -p "`eval_gettext 'Do you wish to copy the files'`? " yn
    case $yn in
        [YyJj]* ) break;;
        [Nn]* ) exit;;
        * ) echo `eval_gettext 'Please answer yes or no'`.;;
    esac
done

# Moves to the directory with corrupted files
cd "$WhereAreFiles"
if [ $? -gt 0 ]; then
	exit 2
fi

# Creates the directory for rescued files
mkdir -p $SafePlace 
if [ $? -gt 0 ]; then
	exit 3
fi

# Creates the original directory structure
find . -type d -exec mkdir -p $SafePlace/{} \; 
if [ $? -gt 0 ]; then
	exit 4
fi

# Finds all files and tries to rescue them
find . -type f -exec $PROG {} $SafePlace/{} \; 

cd $SafePlace
