#!/bin/sh
#
id="$0 // 2018-11-03 // Yargo HB9KNS"

# standard permissions for shared directories
sperms=${SHARPERMS:-3775}
# group for shared directories
shargroup=${SHARGROUP:-`id -g -n`}

# abort with arg.1=code, arg.2=message
sorry() {
 echo ${2:-error} ' -- aborting!'
 exit ${1:-9}
}

if test "$1" = ""
then cat <<EOH
usage: $0 [-g <group>] <directory>

install <directory> belonging to <group> (or the user's
standard group, if not specified) and initialize it
with a git repo with shared=<group> setting, to permit
collaborative work among members of <group>
(if git is not available, just install <directory>)
- standard group is the user's main group or contents of the
  environment variable SHARGROUP, if defined
  (currently $shargroup)
- standard permissions are as defined by the environment
  variable SHARPERMS, if defined, or 3775
  (currently $sperms)
EOH
exit 0
fi

while test "$1" != ""
do case $1 in
 -g) if test "$2" = ""
  then sorry 1 'group empty'
  else shargroup=$2
  fi
  shift
  shift
  ;;
 -*) echo "option $1 ignored!"
  shift ;;
 *) idir="$1"
  shift ;;
 esac
done

if test "$idir" = ""
then sorry 1 'directory empty or not specified'
fi

if test -e "$idir"
then cat <<EOI
 NOTE: '$idir' already exists
 Please make sure ownership and permissions of existing files
 and directories are set correctly for collaborative work!
EOI
fi

if ! mkdir -p "$idir"
then sorry 3 "could not mkdir '$idir'"
fi

echo "trying to change group to $shargroup ..."
chgrp $shargroup "$idir"
echo "trying to set permissions to $sperms ..."
chmod $sperms "$idir"

echo "trying to initialize git repo in '$idir'..."
git init --share=group "$idir"

cat <<EOT

finished!
  Please remember to set your umask to 0002
  to have newly created files writable by group members!

EOT
