#!/bin/sh

read VERSION < .version

echo
echo Installation script for the xFTP-Daemon v$VERSION by Mr.T
echo

echo -n "Where to install the daemon-binary ? [/usr/sbin] "
read DAEMONBINDIR
if [ "$DAEMONBINDIR" = "" ]; then
  DAEMONBINDIR=/usr/sbin
fi
if [ ! -d $DAEMONBINDIR ]; then
  echo
  echo "Directory $DAEMONBINDIR does not exist ! *** ABORTED ***"
  echo
  exit
fi

echo -n "                     administration tools ? [/root/bin] "
read BINDIR
if [ "$BINDIR" = "" ]; then
  BINDIR=/root/bin
fi
if [ ! -d $BINDIR ]; then
  echo
  echo "Directory $BINDIR does not exist ! *** ABORTED ***"
  echo
  exit
fi

echo -n "Where do you want the server's root direcory ? [/ftpserv] "
read SERVERDIR
if [ "$SERVERDIR" = "" ]; then
  SERVERDIR=/ftpserv
fi
if [ ! -d $SERVERDIR ]; then
  echo
  echo -n "The directory $SERVERDIR does not exist ! Create it ? [Y/n] "
  read YESNO
  if [ "$YESNO" = "" ]; then
    YESNO=Y
  fi
  if [ "$YESNO" != "Y" && "$YESNO" != "y" ]; then
    echo
    echo "*** ABORTED ***"
    echo
    exit
  fi
  echo Creating $SERVERDIR
  mkdir $SERVERDIR
  if [ ! -d $SERVERDIR ]; then
    echo
    echo "Creation of $SERVERDIR failed ! *** ABORTED ***"
    echo
    exit
  fi
  echo Creating $SERVERDIR/bin
  mkdir $SERVERDIR/bin
  echo Creating $SERVERDIR/etc
  mkdir $SERVERDIR/etc
  echo Creating $SERVERDIR/var
  mkdir $SERVERDIR/var
  echo Creating $SERVERDIR/var/xftpd
  mkdir $SERVERDIR/var/xftpd
fi

echo -n "To which group the xftp-user's should belong to ? [eleet] "
read PGROUP
if [ "$PGROUP" = "" ]; then
  PGROUP=eleet
fi
if [ "`grep $PGROUP: /etc/group`" = "" ]; then
  echo
  echo "The group $PGROUP does not exist ! *** ABORTED ***"
  echo
  exit
fi

PRGS="xadd xadduser xcred xdeluser xpasswd xuser xtop10 xdown10 xip"

echo
echo Installing ...
echo

#
# Look for an existing link in.xftpd
#

if [ -L ${DAEMONBINDIR}/in.xftpd ]; then
  echo "  Removing link to old daemon"
  rm -f ${DAEMONBINDIR}/in.xftpd
fi

#
# Look for an existing file in.xftpd
#

if [ -f ${DAEMONBINDIR}/in.xftpd ]; then
  echo "  Backing up old daemon"
  mv -f ${DAEMONBINDIR}/in.xftpd ${DAEMONBINDIR}/in.xftpd-old
fi

echo "  Installing daemon to ${DAEMONBINDIR}/in.xftpd-${VERSION}"
install -g bin -m 755 -o bin in.xftpd ${DAEMONBINDIR}/in.xftpd-${VERSION}

echo "  Creating link ${DAEMONBINDIR}/in.xftpd"
ln -fs ${DAEMONBINDIR}/in.xftpd-${VERSION} ${DAEMONBINDIR}/in.xftpd

cp xadd.in xadd
echo "xadduser \$USR $PGROUP \$RATIO $SERVERDIR /etc/ftponly \$HOSTS" >> xadd

for PRG in $PRGS ; do
  if [ -f $BINDIR/$PRG ]; then
    echo "  Backing up old $PRG"
    mv -f $BINDIR/$PRG $BINDIR/$PRG-old
  fi
  echo "  Installing $PRG to $BINDIR/"
  install -g root -m 700 -o root $PRG $BINDIR
done

rm xadd

if [ ! -f /etc/ftponly ]; then
  echo "  Installing ftponly to /etc/"
  install -g bin -m 755 -o bin ftponly /etc
fi

if [ "`grep /etc/ftponly /etc/shells`" = "" ]; then
  echo "  Adding /etc/ftponly to /etc/shells"
  echo "/etc/ftponly" >> /etc/shells
fi

echo
echo Done.
echo
