#!/bin/bash

CONFDIR=/etc/samba
CONFFILE=$CONFDIR/smb.conf
PREPEND=
APPEND=$CONFDIR/smb.conf.append
MASTER=$CONFDIR/smb.conf.master
MKINCLUDE=$CONFDIR/mkinclude

if [ ! -d "$CONFDIR" ]
then
  if [ ! -w "`dirname $CONFDIR`" ]
  then
    echo "Can't find or create config dir $CONFDIR"
    exit 1
  else
    mkdir "$CONFDIR"
  fi
fi

if [ ! -f "$MASTER" ]
then
  echo "Cannot find master conf file $MASTER"
  exit 1
fi

if [ ! -f "$CONFFILE" ]
then
  if [ ! -w "`dirname ${CONFFILE}`" ]
  then
    echo "Cannot write to directory containing config file $CONFFILE"
    exit 1
  fi
  if [ ! -f "$CONFFILE" ]
  then
    if [ ! `touch "$CONFFILE"` ]
    then
      exit 1
    fi
  fi
elif [ ! -w $CONFFILE ]
then
  echo "Can't write to config file $CONFFILE"
  exit 1
else
  echo "" > "$CONFFILE"
fi

if [ -x "$MKINCLUDE" ]
then
  "$MKINCLUDE"
fi

if [ -f "$PREPEND" ]
then
  cat "$PREPEND" > "$CONFFILE"
  testparm -s "$MASTER" >> "$CONFFILE"
else
  testparm -s "$MASTER" > "$CONFFILE"
fi

if [ -f "$APPEND" ]
then
  cat "$APPEND" >> "$CONFFILE"
fi
