#!/bin/bash

function usage() {
    echo "Usage: $0 --localtree /path/to/ --owner 'user' --group 'group' --name 'name' [--shared [true|false]] [--public [true|false]]"
    exit 1
}

[ $# -eq 0 ] && usage

while [ $# -gt 0 ]; do
    case "$1" in
        --localtree)
            LOCALTREE=$2
            shift; shift
        ;;
        --name)
            NAME=$2
            shift; shift
        ;;
        --shared)
            if [ "$2" == "true" -o "$2" == "false" ]; then
                SHARED=$2
                shift; shift
            else
                SHARED="true"
                shift
            fi
        ;;
        --public)
            if [ "$2" == "true" -o "$2" == "false" ]; then
                PUBLIC=$2
                shift; shift
            else
                PUBLIC="true"
                shift
            fi
        ;;
        --owner)
            OWNER=$2
            shift; shift
        ;;
        --group)
            GROUP=$2
            shift; shift
        ;;
        *)
            usage
        ;;
    esac
done

# --name is required
[ -z "$NAME" ] && exit 1

# tree must exist
[ ! -d "$LOCALTREE/$NAME" ] && exit 1

# if owner doesn't exit
[ -z "$OWNER" ] && exit 1

OWNER_EXISTS=`getent passwd $OWNER > /dev/null 2>&1; echo $?`

[ $OWNER_EXISTS -eq 0 ] || exit 1

# same if group doesn't exist
[ -z "$GROUP" ] && exit 1

GROUP_EXISTS=`getent group $GROUP > /dev/null 2>&1; echo $?`

[ $GROUP_EXISTS -eq 0 ] || exit 1

# if info file is there, we're already done
if [ -d "$LOCALTREE/$NAME/info" ]; then
    # Ensure though you change the ownership as specified
    chown -R $OWNER:$GROUP "$LOCALTREE/$NAME"
    if [ "$SHARED" == "true" ]; then
        find "$LOCALTREE/$NAME" -type d -exec chmod g+ws {} \;
        find "$LOCALTREE/$NAME" -type f -exec chmod g+w {} \;
    fi

    if [ "$PUBLIC" == "true" ]; then
        find "$LOCALTREE/$NAME" -type d -exec chmod o+rx {} \;
        find "$LOCALTREE/$NAME" -type f -exec chmod o+r {} \;
    fi

    exit 0
fi

cd "$LOCALTREE/$NAME"

# We cannot --bare init as long as the manifest depends on
# .git/ being present.
[ "$SHARED" == "true" ] && git --bare init --shared || git --bare init

if [ "$PUBLIC" == "true" ]; then
    find "$LOCALTREE/$NAME" -type d -exec chmod o+rx {} \;
    find "$LOCALTREE/$NAME" -type f -exec chmod o+r {} \;
fi

chown -R $OWNER:$GROUP .