#!/bin/sh

################################################################################
#
# Copyright (C) 2014 Cumulus Networks Inc. All rights reserved
#
################################################################################

# Copy the persist configuration into the target file system
# arg $1 - legacy, ignored
# arg $2 - source directory
# arg $3 - destination directory

src_dir="$2"
dst_dir="$3"

tmp_exclude=$(mktemp)
echo "lost+found" > $tmp_exclude
# copy over all files except for those under /home
echo "home" >> $tmp_exclude

tmp_error=$(mktemp)
tar -C $src_dir -X $tmp_exclude -cmf - . | tar -C $dst_dir -xf - > $tmp_error 2>&1
if [ "$?" != "0" ] ; then
    echo "Error: Problems copying over persistent config.  Error output follows:"
    cat $tmp_error
    rm -f $tmp_error $tmp_exclude
    exit 1
fi
rm -f $tmp_error $tmp_exclude

# Handle files and directories under /home differently
if [ -d "$src_dir/home" ] ; then

    # need to map user names to ids
    cp $dst_dir/etc/passwd /etc
    cp $dst_dir/etc/group /etc

    # make sure no dirs/files are owned by root. if a file is
    # owned by root:
    #
    #   - if the file is destined for an existing user then
    #     chown file to that user.
    #
    #   - if the file is destined for a non-existing user then
    #     chown file to nobody.nogroup.
    
    cd $src_dir
    # foreach directory in /mnt/persist/home ... 
    find home -mindepth 1 -maxdepth 1 -type d | while read h ; do
        # peel off the user name
        user="${h#home/}"

        # does the destination home dir exist?
        if [ -d "$dst_dir/home/$user" ] ; then
            uid=$(stat -c "%u" "$dst_dir/home/$user")
            gid=$(stat -c "%g" "$dst_dir/home/$user")
        else
            # use nobody.nogroup
            uid=nobody
            gid=nogroup
        fi

        # make sure no dirs/files are owned by root
        find "$h" \( -user root -o -group root \) -a -print0 | xargs -0 -r -n 1 chown ${uid}.${gid}

            # now copy all files
            cp -a "$h" $dst_dir/home
    done

fi
