#! /bin/sh

DIR=$1
shift
OPTIONS=$*

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

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

for opt in $options; do
    case $opt in
        ignore_file=*)
            IGNORE_FILE_REGEXP=$(echo $opt | sed -e "s/^ignore_file=\(.*\)$/\1/")
            ;;
        ignore_folder=*)
            IGNORE_FOLDER_REGEXP=$(echo $opt | sed -e "s/^ignore_folder=\(.*\)$/\1/")
            ;;
        *)
            ;;
    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"
}

generate_folder_structure


