#!/bin/bash
primary_mount=$1
secondary_mount=$2
mount_name=$3

foreachd_nonvol () {
nonvol_dir=$1
nonvol_name=$2

for file in $nonvol_dir/*; do
        bak_file=${file/${nonvol_name}/${nonvol_name}_bak}
        bak_path=${bak_file%/*}
        if [ -d $file ]; then
                if [ ! -d $bak_file ]; then
                        echo "Folder does not exist in $bak_path, make directory"
                        mkdir $bak_file
                fi
                echo "$file is a folder, enter $file"
                foreachd_nonvol $file $nonvol_name
        elif [ -f $file ]; then
                echo "Check $file"
                mdm=$(echo $file | grep mdm.*.config)
                if [ -n "$mdm" ]; then
                        tmp_file=/tmp/${file#$primary_mount/}
                        cp $file $tmp_file
                        /bin/ckmdm $tmp_file
                        if [ $? -ne 0 ]; then
                                rm -f $tmp_file
                                continue
                        fi
                        file=$tmp_file
                fi
                if [ ! -f $bak_file ]; then
                        cp $file $bak_path
                        echo "File does not exist in $bak_path, copy"
                else
                        diff $file $bak_file > /dev/null
                        if [ $? -ne 0 ]; then
                                echo "File is different, copy to $bak_path"
                                cp $file $bak_path
                        else
                                echo "Files are same, do not copy"
                        fi
                fi
        fi
        if [ -f $tmp_file ]; then
                rm $tmp_file 2>/dev/null
        fi
done
}

foreachd_bak () {
bak_dir=$1
nonvol_name=$2

for file in $bak_dir/*; do
        nonvol_file=${file/${nonvol_name}_bak/${nonvol_name}}
        nonvol_path=${nonvol_file%/*}
        if [ -d $file ]; then
                if [ ! -d $nonvol_file ]; then
                        echo "Folder does not exist in $nonvol_path, delete"
                        rm -rf $file
                else
                        echo "$file is a folder, enter $file"
                        foreachd_bak $file $nonvol_name
                fi
        elif [ -f $file ]; then
                echo "Check $nonvol_file"
                if [ ! -f $nonvol_file ]; then
                        echo "$nonvol_file does not exist, delete it in $bak_dir"
                        rm $file
                fi
        fi
done
}

#ensure that both mounts are mounted before we copy anything
if ! grep -qs $primary_mount /proc/mounts; then
echo "$primary_mount not mounted!"
exit 1
fi

if ! grep -qs $secondary_mount /proc/mounts; then
echo "$secondary_mount not mounted!"
exit 1
fi

#primary_mount is the one guaranteed good for CMS, so if that changes, we copy to
#secondary_mount each time
foreachd_nonvol $primary_mount $mount_name
foreachd_bak $secondary_mount $mount_name
