#!/bin/sh

# @file ellis.cron.daily
#
# Copyright (C) Metaswitch Networks 2014
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

. /etc/clearwater/config

# First find the expired users.  We pipe a SQL command into mysql and log if
# the query fails.
USERS=$(echo "use ellis; SELECT email FROM users WHERE expires < NOW();" |
        mysql -s 2>/tmp/ellis.cron.daily.$$) ||
( logger -p daemon.err -t ellis.cron.daily Expired users SQL query failed... ;
  logger -p daemon.err -t ellis.cron.daily -f /tmp/ellis.cron.daily.$$ )
rm /tmp/ellis.cron.daily.$$

# Now spin through the users we got, deleting them.  (If we got none, this is a
# no-op.)
for USER in $USERS
do
  # Issue a curl request to delete the user, logging if this fails.
  logger -p daemon.notice -t ellis.cron.daily "Deleting expired user $USER"
  OUT=$(curl -s -X DELETE -H "NGV-API-Key: ${ellis_api_key}" http://$local_ip/accounts/$USER) ||
  logger -p daemon.err -t ellis.cron.daily "curl reported error $? when deleting expired user $USER"

  # A successful delete returns no response.  If we got a response, log it.
  [ -z "$OUT" ] || logger -p daemon.err -t ellis.cron.daily "Deleting expired user $USER failed with response $OUT"
done

