Files

73 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
FREEBOX_HOST="${FREEBOX_HOST:-mafreebox.freebox.fr}"
API_BASE="${API_BASE:-https://${FREEBOX_HOST}/api/v4}"
APP_ID="${APP_ID:-fr.bash.reboot}"
TOKEN_FILE="${TOKEN_FILE:-$(dirname "$0")/freebox_app_token.txt}"
CA_FILE="${CA_FILE:-$(dirname "$0")/freebox_ecc_root_ca.pem}"
for cmd in curl jq openssl; do
command -v "$cmd" >/dev/null 2>&1 || { echo "Missing dependency: $cmd" >&2; exit 1; }
done
if [[ ! -f "$TOKEN_FILE" ]]; then
echo "Missing token file: $TOKEN_FILE" >&2
exit 1
fi
if [[ ! -f "$CA_FILE" ]]; then
echo "Missing CA file: $CA_FILE" >&2
exit 1
fi
APP_TOKEN="$(tr -d '\r\n' < "$TOKEN_FILE")"
if [[ -z "$APP_TOKEN" ]]; then
echo "Empty app token in $TOKEN_FILE" >&2
exit 1
fi
echo "Fetching challenge..."
login_response="$(curl --cacert "$CA_FILE" -fsS "${API_BASE}/login/")"
challenge="$(jq -r '.result.challenge // empty' <<<"$login_response")"
if [[ -z "$challenge" ]]; then
echo "Could not get challenge:" >&2
echo "$login_response" >&2
exit 1
fi
echo "Computing password..."
password="$({ printf '%s' "$challenge" | openssl dgst -sha1 -hmac "$APP_TOKEN"; } | awk '{print $2}')"
echo "Opening session..."
session_response="$({
curl --cacert "$CA_FILE" -fsS -X POST "${API_BASE}/login/session/" \
-H 'Content-Type: application/json' \
-d "{\"app_id\":\"${APP_ID}\",\"password\":\"${password}\"}"
})"
session_token="$(jq -r '.result.session_token // empty' <<<"$session_response")"
if [[ -z "$session_token" ]]; then
echo "Authentication failed:" >&2
echo "$session_response" >&2
exit 1
fi
echo "Rebooting..."
reboot_response="$({
curl --cacert "$CA_FILE" -fsS -X POST "${API_BASE}/system/reboot/" \
-H "X-Fbx-App-Auth: ${session_token}" \
-H 'Content-Type: application/json' \
-d '{}'
})"
if jq -e '.success == true' >/dev/null 2>&1 <<<"$reboot_response"; then
echo "Reboot requested."
else
echo "Reboot failed:" >&2
echo "$reboot_response" >&2
exit 1
fi