#!/bin/bash

# api credentials
client_id="<client-id>"
client_secret="<client-secret>"

# install action
# DownloadOnly - Download the software update without installing it
# Default - Download and/or install the software update, depending on the current device state
# InstallASAP - install an already downloaded software update
install_action="Default"

# update key
update_key="iOSUpdate19G82"

# realm
realm="prod"

# api urls
devices_url="https://$realm.addigy.com/api/devices"
updates_url="https://$realm.addigy.com/api/mdm/updates/install"

# parse json script
script='import json, sys
devices=json.load(sys.stdin) 
agents=[device["agentid"] for device in devices if device["Device Model Name"]=="iPhone" or device["Device Model Name"]=="iPad"]
for agent in agents: print(agent)'

# get agents ids
curl --request GET "$devices_url" \
    --header "client-id: $client_id" \
    --header "client-secret: $client_secret" | 
    python3 -c "$script" > /tmp/agent_ids.txt

# enqueue update
while IFS= read -r agent_id
do
    echo "enqueuing update command for agent " "$agent_id"
    curl --request POST "$updates_url" \
        --header "client-id: $client_id" \
        --header "client-secret: $client_secret" \
        --data-raw "{
            \"agent_id\": \"$agent_id\",
            \"install_action\": \"$install_action\",
            \"product_key\": \"$update_key\"
        }"
    echo
done < "/tmp/agent_ids.txt"

# cleanup
rm /tmp/agent_ids.txt