#!/bin/bash -e

if [ $# != 2 ]; then
  echo "Usage: $(basename $0) <hostname> <firmware>"
  exit 1
fi

HOST="$1"
FW="$2"
LOGIN=admin

read -r -s -p "Password for \"$LOGIN\" on $HOST: " PASS
echo

# Escape for JSON
PASS="$(printf '%s' "$PASS" | sed 's/[\\"]/\\&/g')"

COOKIES=$(mktemp)
BODY=$(mktemp)
trap 'rm -f $COOKIES $BODY' EXIT

# Login.  The controller only accepts a password over HTTPS and its
# certificate is self-signed, hence -k.  The password is passed on stdin to
# keep it out of the process list.
CODE=$(curl -sLk -c $COOKIES -o $BODY -w '%{http_code}' -X PUT \
            -H 'Content-Type: application/json' --data @- \
            "https://$HOST/api/auth/login" \
            <<< "{\"user\":\"$LOGIN\",\"password\":\"$PASS\"}")

if [ "$CODE" != 200 ]; then
  echo "Login failed: $(cat $BODY)"
  exit 1
fi

# Send firmware
curl -sLk -b $COOKIES -i -X PUT -H "Content-Type: multipart/form-data" \
     -F "firmware=@$FW" "https://$HOST/api/firmware/update"
