#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

# -*- mode:sh -*-
# 
# Usage:
#   gpdircheck [-E] path ...
#       -E   check if directory is empty
#
# Tests that the arguments:
#   - exist in the filesystem
#   - are directories
#   - current user has read/write permission
#
# When -E is specified we will check that the next directory does NOT exist
#
# Standard System error messages can be examined with:
#   perl -le 'print $!+0, "\t", $!++ for 0..127'
#

# Scan through directories and perfom the checks on each in turn.
OPTION=0;
for i in "$@"
do
  # Handle options
  if [ "${i:0:1}" == "-" ]; then 
    # for any option we expect a directory to follow, so if we already
    # have an option set but not yet cleared it is an error.
	  if [ $OPTION -ne 0 ]; then 
		  echo "Usage: gpdircheck [-E] ..." 1>&2; exit 1;
	  fi;
      if [ "$i" == "-E" ]; then 
		  OPTION=1;
	  else
		  echo "Usage: gpdircheck [-E] ..." 1>&2; exit 1;
	  fi;

  # -E will allow non-existent directories, it is assumed that the
  # parent directory is allow being checked without the -E option.
  elif [ $OPTION -eq 1 ]; then
	  if [ ! -e "$i" ]; then OPTION=0;            # Good result
	  else echo "$i : File exists" 1>&2; exit 17;
	  fi
  elif [ ! -e "$i" ]; then echo "$i : No such file or directory" 1>&2; exit 2;
  elif [ ! -d "$i" ]; then echo "$i : Not a directory" 1>&2; exit 20;
  elif [ ! -r "$i" ]; then echo "$i : No read permissions" 1>&2; exit 13;
  elif [ ! -w "$i" ]; then echo "$i : No write permissions" 1>&2; exit 13;

# We no longer check for empty directories, instead we error when -E
# points to a directory that already exists.

#  elif [ $OPTION -eq 1 ]; then
#    if [ `ls "$i" | wc -l` -ne 0 ]; then 
#       echo "$i : Directory not empty" 1>&2; exit 66;
#    fi;
	OPTION=0;
  fi;
done;

# If we had a -E without a following directory then error.
if [ $OPTION -ne 0 ]; then
    echo "Usage: gpdircheck [-E] ..." 1>&2; 
    exit 1;
fi;

exit 0;
