#!/bin/bash
# Author: Charles Jiron
# iOS Wallpaper Change: Bash

# API credentials
AddigyToken="YOUR_API_V2_TOKEN" # API V2 TOKEN

# Policy ID
PolicyID="PASTE YOUR OWN POLICY ID"

# Where to set the background
# Values: 1= Lock Screen 2= Home Screen 3= Both
where=3

# Read the Base64 image from the file into a variable
imagePath="YOUR_IMAGE_FILE_PATH" # Image Path
encodedImage=$(base64 -i $imagePath) # BASE64 Image  

output_file="Addigy-iOS-Wallpaper-Device-List-Bash.csv"

echo "FILE CHECK & CREATION"
echo "===================="
if [ -f "$output_file" ]; then
  echo "File exists...REMOVING Duplicate."
  rm -f "$output_file"
else
  echo "File does not exist...CREATING File"
 
fi

# Perform the API request and store the response
# -verbose 
DeviceList=$(curl -s -f --location 'POST' \
  'https://api.addigy.com/api/v2/devices' \
  -H 'accept: application/json' \
  -H "x-api-key: $AddigyToken" \
  -H 'Content-Type: application/json' \
  -d '{
  "desired_fact_identifiers": [
     "agentid",
     "device_name",
     "serial_number",
     "policy_id",
     "hardware_model",
     "device_model_name"
  ],
  "page": 1,
  "per_page": 300,
  "query": {
    "filters": [
      {
        "audit_field": "os_version",
        "operation": ">",
        "range_value": "",
        "type": "string",
        "value": "0"
      }
    ],
    "policy_id": "'"$PolicyID"'",
    "search_any": ""
  },
  "sort_direction": "asc",
  "sort_field": "serial_number"
}')

# Function to process and output data to a file
process_device_list() {
    local json_data=$1

    # Clear and add a header row for our CSV File
    echo "========================================"
    echo "Device Wallpaper List - $(date '+%Y-%m-%d %H:%M')" 
    echo "========================================"

    echo "Device Name,Serial Number,Agent ID,Device Model,Policy ID, Wallpaper Change Status" >> "$output_file"

    echo "$json_data" | jq -c '.items[]' | while read -r item; do
        # Extract the desired fields for each item
        deviceName=$(echo "$item" | jq -r '.facts.device_name // "N/A"')
        serial_number=$(echo "$item" | jq -r '.facts.serial_number // "N/A"')
        policy_id=$(echo "$item" | jq -r '.facts.policy_id // "N/A"')
        agent_id=$(echo "$item" | jq -r '.facts.agentid // "N/A"')
        device_model=$(echo "$item" | jq -r '.facts.device_model_name // "N/A"')
        
        # Extract values from desired fields
        iPhones_iPads_Only=$(echo "$device_model" | grep '"value"' | awk -F'"' '{print $4}')
        Agent_ID_Only=$(echo "$agent_id" | grep '"value"' | awk -F'"' '{print $4}')
        Serial_Number_Only=$(echo "$serial_number" | grep '"value"' | awk -F'"' '{print $4}')
        Device_Name_Only=$(echo "$deviceName" | grep '"value"' | awk -F'"' '{print $4}')
        Policy_ID_Only=$(echo "$policy_id" | grep '"value"' | awk -F'"' '{print $4}')
        

        if [ "$iPhones_iPads_Only" = "iPhone" ] || [ "$iPhones_iPads_Only" = "iPad" ]; then
          echo "Device Name: $Device_Name_Only"
          echo "Serial Number: $Serial_Number_Only"   
          echo "Device Model: $iPhones_iPads_Only"
          echo "Agent ID: $Agent_ID_Only"

          # Endpoint Variable
          Wallpaper_endpoint=$(curl -s -f -X 'POST' \
          'https://api.addigy.com/api/v2/mdm/settings/wallpaper' \
           -H 'accept: application/json' \
           -H "x-api-key: $AddigyToken" \
           -H 'Content-Type: application/json' \
           -d '{
                  "agent_id": "'"$Agent_ID_Only"'",
                  "image": "'"$encodedImage"'",
                  "where": '"$where"'
               }')
            
            if [ $? -eq 0 ]; then
              echo "Wallpaper Change - Successful!"
              echo "Logging to $output_file......"
              echo "========================================"
              success="Successful"

              # Output the values for the current item and append to the file
              {
                echo "$Device_Name_Only",$Serial_Number_Only",$Agent_ID_Only",$iPhones_iPads_Only",$Policy_ID_Only","$success"

              } >> "$output_file"
            else
              echo "Wallpaper Chnage - Failure!"
              echo "Logging to $output_file......"
              echo "========================================"
              failure="Failure"

              # Output the values for the current item and append to the file
              {
                echo "$Device_Name_Only",$Serial_Number_Only",$Agent_ID_Only",$iPhones_iPads_Only",$Policy_ID_Only","$failure"

              } >> "$output_file"
            fi
        fi
    done
}

# Process both JSON data sources into one file
process_device_list "$DeviceList"
exit 0