#! /bin/sh

DIR=$1
shift
OPTIONS=$*


# Decode the options given in parameters
IGNORE_FILE_REGEXP=""
IGNORE_FOLDER_REGEXP=""

FIND=/usr/bin/find
STAT=/usr/bin/stat

for opt in $OPTIONS; do
    case $opt in
        ignore_file=*)
            IGNORE_FILE_REGEXP=${opt#ignore_file=*}
            ;;
        ignore_folder=*)
            IGNORE_FOLDER_REGEXP=${opt#ignore_folder=*}
            ;;
        *)
            ;;
    esac
done

# This function filter the file to ignore according to the regexp given in
# parameter.
filter_ignore() {
    local ignore_regexp
    ignore_regexp=$1
    while read line; do
        if [ -z "$ignore_regexp" ] || [ "$(printf "$line" | sed -e "s/'$//" | egrep "$ignore_regexp")" = "" ]; then
            echo "$line"
        fi
    done
}

# This function create a shell script that will generate the structure of
# the folder $dir
generate_folder_structure() {
    $FIND $DIR -type d -exec echo "mkdir -p '{}'" \; | filter_ignore $IGNORE_FOLDER_REGEXP

    $FIND $DIR -type d -exec $STAT --format "chown %U '{}'" {} \; | filter_ignore "$IGNORE_FOLDER_REGEXP"
    $FIND $DIR -type d -exec $STAT --format "chgrp %G '{}'" {} \; | filter_ignore "$IGNORE_FOLDER_REGEXP"
    $FIND $DIR -type d -exec $STAT --format "chmod %a '{}'" {} \; | filter_ignore "$IGNORE_FOLDER_REGEXP"
}

# This function create a shell script that will generate recursively empty
# file present in $dir
generate_file_structure() {
    $FIND $DIR -type f -print | filter_ignore "$IGNORE_FILE_REGEXP" | while read file; do
        echo "touch '$file'"
    done

    $FIND $DIR -type f -exec $STAT --format "chown %U '{}'" {} \; | filter_ignore "$IGNORE_FILE_REGEXP"
    $FIND $DIR -type f -exec $STAT --format "chgrp %G '{}'" {} \; | filter_ignore "$IGNORE_FILE_REGEXP"
    $FIND $DIR -type f -exec $STAT --format "chmod %a '{}'" {} \; | filter_ignore "$IGNORE_FILE_REGEXP"
}


generate_folder_structure
generate_file_structure


