#!/usr/bin/bash

SOLO_MARKER="/etc/cloudlinux-edition-solo"
CONTAINER_MARKER="/etc/cloudlinux-container"

if [[ -f $SOLO_MARKER || -f $CONTAINER_MARKER ]]; then
    /usr/sbin/cagefsctl --delete-namespace $1 > /dev/null 2>&1
fi

user_uid=`/usr/bin/id -u $1 2> /dev/null`
# Count all entries for found id in /etc/passwd
uid_count=$(/usr/bin/getent passwd | awk -F: '{printf "%s:%s\n",$1,$3}' | grep -w "${user_uid}" | wc -l)

if [[ "${uid_count}" -eq 1 ]]; then
  if [ -e /usr/sbin/cagefsctl ]; then
    /usr/sbin/cagefsctl --set-default-user-status $1 > /dev/null 2>&1
    /usr/sbin/cagefsctl --unmount $1 > /dev/null 2>&1
  fi

  if [[ -e /usr/sbin/lvectl && ! -f $SOLO_MARKER && ! -f $CONTAINER_MARKER ]]; then
    if [ -n "${user_uid}" ]; then
      /usr/sbin/lvectl delete "${user_uid}" > /dev/null 2>&1
      /usr/sbin/lvectl destroy "${user_uid}" > /dev/null 2>&1
    fi
  fi
fi

if [ -e /etc/cagefs/userdel.old ]; then
  cmd=`cat /etc/cagefs/userdel.old`
  /bin/bash -c "$cmd"
fi
