#!/bin/bash

set -e

# configuration
USER="sipwise"
GROUP="sipwise"
FALLBACK_HOME="/var/sipwise"
NGCPDATA_HOME="/ngcp-data/home/sipwise"

usage() {
  echo "Usage: $0 {--enable|--disable}

Usage example:

  $0 --enable       configure user $USER login (SSH/sudo)
  $0 --disable      unconfigure user $USER login (SSH/sudo)

"
}

delete_user() {
  if ! getent passwd "$USER" &>/dev/null ; then
    echo "* User '${USER}' doesn't exist, nothing to delete."
  else
    echo "* Deleting user '${USER}'."
    userdel -r "$USER"
  fi

  # remove compat symlink, if left dangling
  if [[ -L "${FALLBACK_HOME}" ]] &&
     [[ "$(readlink "${FALLBACK_HOME}")" = "${NGCPDATA_HOME}" ]] &&
     ! readlink -e "${FALLBACK_HOME}" &>/dev/null ; then
    echo "* Removing compat symlink ${FALLBACK_HOME} which points to removed ${NGCPDATA_HOME}"
    rm -f "${FALLBACK_HOME}"
  fi
}

add_user() {
  local home="${FALLBACK_HOME}"
  if [[ -d "/ngcp-data/" ]]; then
    home="${NGCPDATA_HOME}"
    home_base="$(dirname "${NGCPDATA_HOME}")"
    if [[ ! -d "${home_base}" ]]; then
      echo "* Creating missing ${home_base}."
      mkdir -p "${home_base}"
      chown root:root "${home_base}"
      chmod 0755 "${home_base}"
    fi
  fi
  echo "* Creating user ${USER} with home directory ${home}."
  useradd -m -s /bin/bash -d "${home}" -u 10000 -U -c "Sipwise Support" "${USER}"
  chown -R ${USER}:${GROUP} "${home}"
  chmod 0750 "${home}"

  # create compat symlink, templates and others places expect to install or read
  # files from sipwise user's home, and it's difficult to have dynamic paths
  # there
  if [[ "${home}" == "${NGCPDATA_HOME}" ]] ; then
    if [[ -d "${FALLBACK_HOME}" ]] ; then
      echo "Error: homedir for sipwise user created in ${NGCPDATA_HOME}, but old ${FALLBACK_HOME} exists (and it is a directory)" >&2
      exit 1
    elif [[ -e "${FALLBACK_HOME}" ]] ; then
      echo "Error: homedir for sipwise user created in ${NGCPDATA_HOME}, but old ${FALLBACK_HOME} exists and it is a NOT directory" >&2
      exit 1
    else
      echo "* Creating compatibility symlink from ${FALLBACK_HOME} to ${NGCPDATA_HOME}"
      ln -s "${NGCPDATA_HOME}" "${FALLBACK_HOME}"
    fi
  fi
}

setup_groups() {
  echo "* Adding user ${USER} to groups _ngcp-api and _ngcp-admin."
  adduser ${USER} _ngcp-api
  adduser ${USER} _ngcp-admin
}

ssh_setup() {
  echo "* Creating .ssh directory for user ${USER}."
  local home="/nonexistent"
  home=$(getent passwd "${USER}" | cut -d':' -f6)
  if [[ -d "${home}" ]] ; then
    mkdir -p "${home}/.ssh"
    chmod 0700 "${home}/.ssh"
    chown -R ${USER}:${GROUP} "${home}/.ssh"
  else
    echo "Error: Could not get home directory for user ${USER}, or it is not a directory" >&2
    exit 1
  fi
}

sudoers_setup() {
  local file="/etc/sudoers.d/${USER}"

  if [ -f "${file}" ] ; then
    if ! grep -q '^# NGCP_MANAGED_FILE' "${file}" ; then
      if [ "$(cat "${file}")" = "sipwise ALL=(ALL) NOPASSWD:ALL" ] ; then
        echo "Detected old/outdated version of the file '${file}', removing it"
        rm "${file}"
      else
        echo "Error: '${file}' exists already but is not an NGCP_MANAGED_FILE" >&2
        exit 1
      fi
    fi
  fi

  echo "* Updating '${file}'."
  # shellcheck disable=SC2174
  mkdir -m 0755 -p /etc/sudoers.d
  touch "${file}"
  chown root:root "${file}"
  chmod 0440 "${file}"
  echo '# NGCP_MANAGED_FILE - do not remove this line if it should be automatically handled' > "${file}"
  echo "${USER} ALL=(ALL) NOPASSWD:ALL" >> "${file}"
}

delete_sudoers() {
  local file="/etc/sudoers.d/${USER}"
  echo "* Removing file '${file}'."
  rm -f "${file}"
}

disable_password() {
  if grep -Eq "^${USER}" /etc/passwd >/dev/null 2>&1 ; then
    echo "* Disabling password for user '${USER}' in /etc/passwd."
    passwd -l "$USER"
  echo
    echo "* User '${USER}' is not in /etc/passwd (LDAP?), skipping disabling password here."
  fi
}

# cmdline processing
ENABLE=false
DISABLE=false

if ! TEMP=$(getopt -o ab:c:: --long help,enable,disable -n "$0" -- "$@") ; then
  echo "Terminating..." >&2
  exit 1
fi

eval set -- "$TEMP"

while true ; do
  case "$1" in
    --help)
      usage
      exit 0
      ;;
    --enable)
      ENABLE=true
      shift
      ;;
    --disable)
      DISABLE=true
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      echo "Internal error!" >&2
      exit 1
      ;;
  esac
done

# Main execution
if "$ENABLE" ; then
  USER_EXISTS=0
  if getent passwd "$USER" &>/dev/null ; then
    USER_EXISTS=1
    echo "* User '${USER}' already exists."
  else
    add_user
  fi
  setup_groups
  ssh_setup
  sudoers_setup
  disable_password
  if [ -n "$USER_EXISTS" ] ; then
    echo "* Support access successfully updated"
  else
    echo "* Support access successfully enabled."
  fi
elif "$DISABLE" ; then
  delete_user
  delete_sudoers
  echo "* Support access successfully disabled."
else
  usage >&2
  exit 1
fi
