#!/bin/sh

if [ "$(whoami)" != "root" ]; then
 echo "You need to be root or execute this command with sudo."
 exit 1
fi

usage() {
  cat << EOF
Usage:		$(basename ${0}) [[Options] [Value]]

Options:	-au|-lu|-h|--help
-au:		Active Directory user name.
-lu:		Local user name.
-h|--help:	Prints this text.

Examples:	$(basename ${0}) -au abyz0001 -lu bob
EOF
}

while [ "$#" -gt "0" ]; do
  case "$1" in
    "-au")
      shift
      AD_USER_NAME="${1}"
    ;;
    "-lu")
      shift
      LOCAL_USER_NAME="${1}"
    ;;
    "-h"|"--help")
      usage
    ;;
  esac
  shift
done

if [ "$(echo ${AD_USER_NAME} | wc -w)" -le "0" ]; then
  echo "Active Directory user name is missing. Need to specify option \"-au\"."
  usage
  exit 2
fi

if [ "$(echo ${LOCAL_USER_NAME} | wc -w)" -le "0" ]; then
  echo "Local user name is missing. Need to specify option \"-lu\"."
  usage
  exit 3
fi

LOCAL_USER_UID=$(id -u ${LOCAL_USER_NAME})
LOCAL_USER_GID=$(id -g ${LOCAL_USER_NAME})

if [ "$(echo ${LOCAL_USER_UID} | wc -w)" -le "0" ]; then
  echo "Local user UID is missing. Unknown error."
  exit 4
fi

if [ "$(echo ${LOCAL_USER_GID} | wc -w)" -le "0" ]; then
  echo "Local user GID is missing. Unknown error."
  usage
  exit 5
fi

apt-get update
apt-get	install	-y cifs-utils autofs
if [ ! -f /etc/auto.master ]; then
  echo "/autofs /etc/auto.cifs --timeout=300 --ghost" >> /etc/auto.master
else
  if [ $(grep -c '/etc/auto.cifs' /etc/auto.master) -le 0 ]; then
    echo "/autofs /etc/auto.cifs --timeout=300 --ghost" >> /etc/auto.master
  fi
fi
echo "${AD_USER_NAME}  -fstype=cifs,rw,file_mode=0640,dir_mode=0750,uid=${LOCAL_USER_UID},gid=${LOCAL_USER_GID},cruid=${LOCAL_USER_UID},sec=krb5i,vers=3.0 ://main.inparadise.se/${AD_USER_NAME}" >> /etc/auto.cifs
service autofs restart
echo "Autofs installation is now complete. You can now browse your home folder via \"/autofs/${AD_USER_NAME}\"."
exit 0
