#!/bin/sh

SERVER_URL=$1
MOUNT_POINT=$2
DAV_USERNAME=$3
DAV_PASSWORD=$4

FS_TYPE="davfs"
MOUNT_OPTIONS="users,noauto"

get_mount_user(){

  ## test if mount point exists
  if [ ! -d ${MOUNT_POINT} ]
  then
    echo ""
    echo "ERROR (1): mount point does not exist"
    echo ""
    exit 1
  fi

  ## get mount point owner
  MOUNT_USER=`ls -ld ${MOUNT_POINT} | awk '{print $3}'`
  MOUNT_USER_GROUP=`ls -ld ${MOUNT_POINT} | awk '{print $4}'`
  MOUNT_USER_FOLDER=`su - ${MOUNT_USER} -c 'eval "echo $HOME"'`

}

add_connection(){

  get_mount_user

  ## test if connection already exists
  cat /etc/fstab | grep " ${FS_TYPE} " | grep "${SERVER_URL}" | grep "${MOUNT_POINT}" > /dev/null
  if [ $? = 0 ]
  then
    echo ""
    echo "ERROR (2): That connection is already setup"
    echo ""
    exit 2
  fi

  echo "${SERVER_URL} ${MOUNT_POINT} ${FS_TYPE} ${MOUNT_OPTIONS} 0 0" >> /etc/fstab

  ## make sure mount.davfs has setuid bit
  DAVFS_MOUNT_CMD_PERMS=`ls -l /usr/sbin/mount.davfs* | awk '{print $1}'`
  if [ "${DAVFS_MOUNT_CMD_PERMS}" != "-rwsr-sr-x" ]
  then
    chmod +s /usr/sbin/mount.davfs*
  fi

  ## make sure ~/.davfs2/secrets exists with correct permissions
  if [ ! -d ${MOUNT_USER_FOLDER}/.davfs2 ]
  then
    mkdir ${MOUNT_USER_FOLDER}/.davfs2
  fi
  if [ ! -f ${MOUNT_USER_FOLDER}/.davfs2/secrets ]
  then
    touch ${MOUNT_USER_FOLDER}/.davfs2/secrets
  fi
  chmod 0600 ${MOUNT_USER_FOLDER}/.davfs2/secrets
  chown -R ${MOUNT_USER}:${MOUNT_USER_GROUP} ${MOUNT_USER_FOLDER}/.davfs2

}

save_credentials_no_prompt(){

  ## add credentials to davfs2 secrets file
  echo "${SERVER_URL} ${DAV_USERNAME} ${DAV_PASSWORD}" >> ${MOUNT_USER_FOLDER}/.davfs2/secrets

}

save_credentials_prompt_pass(){

  echo "Please enter the webdav password:"
  read DAV_PASSWORD

  ## add credentials to davfs2 secrets file
  echo "${SERVER_URL} ${DAV_USERNAME} ${DAV_PASSWORD}" >> ${MOUNT_USER_FOLDER}/.davfs2/secrets

}

if [ $# = 2 ]
then
  add_connection
elif [ $# = 3 ]
then
  add_connection
  save_credentials_prompt_pass
elif [ $# = 4 ]
then
  add_connection
  save_credentials_no_prompt
else
  echo ""
  echo "Usage (1): $0 server_url mount_point"
  echo "Example  : $0 http://webdav.example.com:80/shares /home/bill/Shares"
  echo ""
  echo "Usage (2): $0 server_url mount_point username"
  echo "Example  : $0 http://webdav.example.com:80/shares /home/bill/Shares bill"
  echo ""
  echo "Usage (3): $0 server_url mount_point username password"
  echo "Example  : $0 http://webdav.example.com:80/shares /home/bill/Shares bill opensesame"
  echo "!WARNING!: this method may save your password to the HISTFILE (command history)"
  echo ""
  echo "NOTE:    : options (2) and (3) will add an entry totthe ~/,davfs2/secrets file for password-less login."
  echo ""
fi
