#!/bin/bash
# Parameters ###################################################
device="xxxxxxxxxxxxxxxxxxxxxxxx" # Spark device ID
token="yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" # Spark Access Token
username="your_gmail_username" # Username (@gmail.com)
enc_pass="your_enc_password" # Key for decrypting command line password
labels=("Bank" "Personal" "Service" "Notification" "^t") # List of (5) Gmail labels*
loopdelay=90 # Check email every X seconds (>60)
startdelay=30 # Initial delay (30 seconds)
################################################################
# (*) Useful system labels for Gmail:
# ALL_MAIL ^all
# DRAFTS ^r
# INBOX ^i
# INBOX_CATEGORY_FORUMS ^sq_ig_i_group
# INBOX_CATEGORY_PRIMARY ^sq_ig_i_personal
# INBOX_CATEGORY_PROMOTIONS ^sq_ig_i_promo
# INBOX_CATEGORY_SOCIAL ^sq_ig_i_social
# INBOX_CATEGORY_UPDATES ^sq_ig_i_notification
# PRIORITY_INBOX ^iim
# SENT ^f
# SPAM ^s
# STARRED ^t
# TRASH ^k
# Variables
newMsgs=(0 0 0 0 0)
gmail_err=0
pass=$1 # Command line password (encrypted)
if [ "$pass" == "" ]
then
# Interactive
echo -n Interactive mode
echo ""
echo -n Enter Gmail \(unencrypted\) password:
read -s pass
echo ""
echo Thanks\!
else
# Decode command line password
pass=$(echo $pass | openssl enc -aes-128-cbc -a -d -salt -pass pass:$enc_pass)
# Debug
# echo "I obtained the following password: $pass"
sleep $startdelay
fi
# Loop every X seconds
while [ true ]
do
# Check number of Gmail emails with labels "Bank", "Personal", "Service" "Notification" and "Starred" (system label)
output=$(curl --silent https://$username:$pass@mail.google.com/mail/feed/atom/{${labels[0]},${labels[1]},${labels[2]},${labels[3]},${labels[4]}})
# Debug
# echo $output
output=$(echo "$output" | sed -n 's:.*\(.*\).*\(.*\).*\(.*\).*\(.*\).*\(.*\).*:\1\n\2\n\3\n\4\n\5:p')
# If no connection to Gmail (or wrong username/password)
if [ "$output" == "" ]; then
# Set (yellow) warning LED
gmail_err=1
newMsgs=(0 0 0 0 0)
else
# Split output results
gmail_err=0
outArray=($output)
newMsgs=("${outArray[@]}")
# Debug
# echo "New emails: ${newMsgs[0]}, ${newMsgs[1]}, ${newMsgs[2]}, ${newMsgs[3]}, ${newMsgs[4]}"
# Limit values to 9
for (( i=0; i<${#newMsgs[@]}; i++ ))
do
if [ ${newMsgs[i]} -gt 9 ]; then
newMsgs[i]='9'
fi
done
# Debug
# echo "New emails (max 9): ${newMsgs[0]}, ${newMsgs[1]}, ${newMsgs[2]}, ${newMsgs[3]}, ${newMsgs[4]}"
fi
# Activate email LEDs (RGB, YELLOW)
output=$(curl -s https://api.spark.io/v1/devices/$device/mail \
-d access_token=$token \
-d params=E$gmail_err\B${newMsgs[0]}\P${newMsgs[1]}\S${newMsgs[2]}\N${newMsgs[3]}\T${newMsgs[4]})
# Check returned device ID for Spark update to be successful
devID=$(echo "$output" | sed -n 's:.*\"id\"\:\ \"\(.*\)\".*:\1:p')
if [ "$devID" != "$device" ]; then
echo "Error updating Spark:"
echo $output
# Sleep more
sleep $(( 3*$loopdelay ))
fi
sleep $loopdelay
# end while loop
done