#!/bin/bash
# Needs jq package installed

sudo -u apache php occ user:list > /tmp/list_user.txt

while read line; do
  echo "$line"
  uid=`echo "${line:2}" | cut -d":" -f1`
  #echo "$uid"
  settings_user=`sudo -u apache php occ user:setting "$uid" --output=json`
  #echo $settings_user
  info_user=`sudo -u apache php occ user:info "$uid" --output=json`
  #echo $info_user
  uldap=`echo $settings_user | jq -r '.user_ldap.uid'`
  #echo $uldap
  last_seen=`echo $info_user | jq -r '.last_seen'`
  #echo $last_seen
  if [ $last_seen = "1970-01-01T00:00:00+00:00" ]; then
    homePath=`echo $info_user | jq -r '.user_directory'`
    if [ -d $homePath ]; then
      du_homePath=`du -s $homePath | cut -f 1`
    else
      du_homePath=0
    fi
    if (( $du_homePath == 0 )); then
      #echo "Remove user $uldap ($uid)"
      #sudo -u apache php occ user:delete $uid
      #
      if [ -d $homePath ]; then
        echo "Remove empty folder for user $uldap ($uid)"
        rm -rf $homePath 
      fi
    fi
  fi
  #exit
done < /tmp/list_user.txt
