#!/bin/bash
# Needs to be run with a cron job
# CURL Applications used
CURL=/usr/bin/curl

CONFIG_FILE=/etc/glam/glam-iotd/config.json

# Read the username and password from the config file
USERNAME=$(cat $CONFIG_FILE | grep GlamUsername)
IFS=':'
read -ra SPLIT_STRING <<< "$USERNAME"
VALUE=${SPLIT_STRING[1]}
VALUE=${VALUE//,}
VALUE=${VALUE//\"}
USERNAME=${VALUE// }

PASSWORD=$(cat $CONFIG_FILE | grep GlamPassword)
IFS=':'
read -ra SPLIT_STRING <<< "$PASSWORD"
VALUE=${SPLIT_STRING[1]}
VALUE=${VALUE//,}
VALUE=${VALUE//\"}
PASSWORD=${VALUE// }
# Clear the internal field seperator
unset IFS

# Number of minutes a device should be offline before they are flagged.
# Currently set for 24 hours
TIMEOUT=2880
# Server credentials
SERVER_URL='http://127.0.0.1:8080/glamservice'

# Convert password to create Auth header
# MD5_PASSWORD=$(echo -n $PASSWORD | md5sum | awk '{print $1}')
# Overwrite with pre-md5 password
MD5_PASSWORD=$PASSWORD
COMBO="${USERNAME}:${MD5_PASSWORD}"

FULL_URL="$SERVER_URL/iot/inactive"
BASE64=$(echo -n $COMBO | base64)
TOKEN_HEADER="Authorization: Basic $BASE64"
# Check for inactive devices
$CURL -H "Content-Type: application/json" -H "$TOKEN_HEADER" -d "$TIMEOUT" $FULL_URL
