#!/bin/sh
#
# syncfiles is a synchronize the files on a snapshot directory with the shared directory
#
# Copyright (C) 2003 Daniel Walsh <dwalsh@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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
#
#
if [ $# != 3 ]; then
        echo $"Usage: $0 DISKLESSDIRECTORY SNAPSHOTNAME KERNELVERSION"
        exit 1
fi
INSTALLDIR=/usr/share/system-config-netboot/diskless
base=`basename "$1"`
if [ "$base" == "root" ]; then
    wd=`dirname "$1"`
else
    wd="$1"
fi
ROOTDIR=$wd/root
if [ ! -d "$ROOTDIR" ]; then
        echo $"$wd must point to a directory containing a root subdirectory"
        exit 1
fi
SNAPSHOTNAME=$2
RELEASE=$3

SNAPSHOTDIR=$wd/snapshot
#
# This function is used to mount files/directories from the snapshot directory 
#  over the root directory.
#
syncfile () {    
    source=$1
    if [[ "$source" = */ ]]; then
       source=${source%/}
    fi
    dest=${SNAPSHOTDIR}/${2}/${source}
    src=${ROOTDIR}/${source}
    dir=`dirname "$dest"`
    if [ ! -e "$src" ]; then
       if [[ "$1" = */ ]]; then
	   mkdir -p $src;
       else
	   touch "$src";
       fi;
    fi;
#
#  Check if file already exists in snapshot directory.  If not attempt to copy
#    from root directory to snapshot directory.
#
    if [ ! -e "$dest" ]; then
	mkdir -p "$dir"
	if [ -e "$src" ] ; then 
	    echo "Copying $src"
	    echo rsync -a "$src" "$dir"
	    rsync -a "$src" "$dir"
	else 
	    echo "Creating ${1}"
	    if [[ "$1" = */ ]]; then
               mkdir -p $dest;
            else
	       touch "$dest"
	    fi;
	fi
    else
#  If dev directory already exists in snapshot directory, check if the root 
#   /dev directory is newer.  If it is rsync the root directory over the 
#   snapshot directory.
	if [ ${source} == "/dev" -a "$src" -nt "$dir" ]; then
	    rsync -v -progress -a "$src" "$dir"
	fi
    fi
}


#
#  Mount the snapshot directory from the server and then mount files 
#  in the snapshot/files file over the the shared ones
#

for i in `grep -v "^#" "$SNAPSHOTDIR"/files`; do 
   syncfile $i $SNAPSHOTNAME
done
if [ -e "$SNAPSHOTDIR"/files.custom ]; then
   for i in `grep -v "^#" "$SNAPSHOTDIR"/files.custom`; do 
       syncfile $i $SNAPSHOTNAME
   done
fi
cd "$ROOTDIR"
for i in `ls lib/modules/$RELEASE/modules.*`; do
    syncfile $i $SNAPSHOTNAME
done
