#!/bin/bash

# to use:
# curl https://ccid.apdu.fr/files/parse.sh | bash -

set -e

function cleanup {
	rm "$TEMP_PARSE" "$TEMP_ERROR"
}

OS_ARCH=$(uname)-$(uname -m)
URL="https://ccid.apdu.fr/files/$OS_ARCH/parse"
TEMP_PARSE=$(mktemp)
TEMP_ERROR=$(mktemp)

trap cleanup EXIT

echo "Using: $OS_ARCH"

curl --silent --show-error --head "$URL" > "$TEMP_PARSE"
if ! grep "HTTP/1.1 200 OK" "$TEMP_PARSE" > /dev/null
then
	echo "parse binary not found for $OS_ARCH"
	exit
fi

curl --silent --show-error "$URL" --output "$TEMP_PARSE"
chmod +x "$TEMP_PARSE"

"$TEMP_PARSE" -p 2> "$TEMP_ERROR" || true
cat "$TEMP_ERROR"

if grep --silent "Please, restart the command as root" "$TEMP_ERROR"
then
	echo "Need to re-run as root"
	sudo "$TEMP_PARSE" -p
	sudo chown "$(whoami)" output.bin
fi

