#!/bin/bash
# Create a new newsgroup, global or private.
# $Id: snnewgroup.in,v 1.11 1998/08/05 05:06:26 harold Exp $

if [ "$UID" -gt 0 ]; then
  if [ "$UID" != "9" ]; then
    echo "Please su"
    exit 1
  fi
  needchown=
else
  needchown=yes
fi

SNROOT=/var/spool/sn
export SNROOT

PATH="/usr/lib/sn:$PATH"
export PATH

progname=`basename $0`
function usage () {
  [ "$@" ] && echo "$@" >&2
  echo "$progname [-xz] news.group.name [server] [port]" >&2
  echo "-x      OK to use minimal headers from XOVER command" >&2
  echo "-z      OK to compress the body of the article" >&2
  echo "server  If specified, means this is a global newsgroup" >&2
  echo "        If not given, this is a private group" >&2
  echo "port    Defaults to 119 if server is specified" >&2
  exit 1
}

function fail () { echo "$@" >&2; exit 2 }

while : ; do
  case "$1" in
  -*)
    case "$1" in
    *x*) xoverok=1;;
    *z*) compressok=1;;
    *) usage;;
    esac
    shift
    ;;
  *) break;;
  esac
done

newsgroup=$1
server=$2
port=$3

[ -z "$newsgroup" ] && usage
case "$server" in
*:*) usage;;
esac

if [ "$port" ]; then
  [ "$port" -gt 0 ] >/dev/null 2>/dev/null ||
    fail "port must be numeric and greater than 0"
else
  port=119
fi

newsgroup=`echo $newsgroup |tr '[A-Z]' '[a-z]'`
if [ "$server" ]; then
  server=`echo $server |tr '[A-Z]' '[a-z]'`
fi

groupdir="$SNROOT/$newsgroup"

#
# Create the spool if it doesn't already exist
#

if [ ! -d "$SNROOT" ]; then
  mkdir "$SNROOT" || fail "Can't make directory $SNROOT"
  [ "$needchown" ] && chown 9.13 $SNROOT
fi

if [ -d "$groupdir" ]; then
  fail "$groupdir already exists"
else
  mkdir "$groupdir" || fail "Can't create directory"
fi

if [ -n "$server" ]; then
  #
  # Is a global group
  #
  if [ ! -e $SNROOT/.outgoing ]; then
    mkdir $SNROOT/.outgoing ||
      fail "Can't make directory $SNROOT/.outgoing"
    [ "$needchown" ] && chown 9.13 $SNROOT/.outgoing
  fi
  if [ ! -e $SNROOT/.outgoing/$server:$port ]; then
    mkdir $SNROOT/.outgoing/$server:$port ||
      fail "Can't make directory $SNROOT/.outgoing/$server:$port"
    [ "$needchown" ] && chown 9.13 $SNROOT/.outgoing/$server:$port
  fi

  ln -s ../.outgoing/$server:$port $groupdir/.outgoing ||
    fail "Can't create $groupdir/.outgoing"

  if [ ! -f "$groupdir/.serial" ]; then
    echo "0" >$groupdir/.serial ||
      fail "Can't create $groupdir/.serial"
  fi
  echo "0" >$groupdir/.max ||
    fail "Can't create $groupdir/.max"
fi

if [ -n "$compressok" ]; then
  touch $groupdir/.compress ||
    fail "Can't create $groupdir/.compress"
fi

if [ -n "$xoverok" ]; then
  touch $groupdir/.xoverok ||
    fail "Can't create %groupdir/.xoverok"
fi

echo -n >$groupdir/.created ||
  fail "Can't create $groupdir/.created"

touch $groupdir/.times ||
  fail "Can't create $groupdir/.times"

[ "$needchown" ] && chown -R 9.13 $groupdir
:
