#!/bin/sh

export PATH="/bin:/usr/bin:/sbin:/usr/sbin"

cd $(dirname $0)

DEVICE_PATH=$1
KEY_BY_TEAM=3
MOUNT_DIR="/mnt"
COUNT1_FILE="count1"
COUNT2_FILE="count2"
BASE_URL="http://192.168.23.1:8081/api/certs/"
FILES_TO_COPY="README.txt"

which curl > /dev/null || { echo 'curl required!'; exit 1; }
which jq > /dev/null || { echo 'jq required!'; exit 1; }
which fatlabel > /dev/null || { echo 'dosfstools required!'; exit 1; }
which mkfs.vfat > /dev/null || { echo 'dosfstools required!'; exit 1; }

echo -n "[+] Starting at "
date

test -e "${COUNT1_FILE}" || echo -n '1' > "${COUNT1_FILE}"
test -e "${COUNT2_FILE}" || echo -n '1' > "${COUNT2_FILE}"

COUNT=$(cat "${COUNT1_FILE}")
COUNT2=$(cat "${COUNT2_FILE}")

echo ">>> Doing operations for TEAM ${COUNT}"

ORIG_LABEL=$(fatlabel "${DEVICE_PATH}")

echo "[+] Dumping ${DEVICE_PATH}"

if [ $(echo -n "${ORIG_LABEL}" | cut -c 1-3) = "FIC" ]
then
    echo "[-] WARNING, this key has already FIC label: ${ORIG_LABEL}!!"
    echo "Exiting...."
    exit 42
fi

echo -n "Getting cert id: "
CERT_ID=$(curl -q "${BASE_URL}" | jq -r .[].id | head -n "${COUNT}" | tail -1)
echo $CERT_ID

LABEL="FIC_"$(echo -n ${CERT_ID})
echo "format USB key with label: ${LABEL}"
mkfs.vfat -n "${LABEL}" "${DEVICE_PATH}" > /dev/null

if [ $? -ne 0 ]
then
    echo "[-] FORMAT ERROR! Aborting..."
    exit 42
fi

echo "${DEVICE_PATH} to ${MOUNT_DIR}"
mount "${DEVICE_PATH}" "${MOUNT_DIR}"
if [ $? -ne 0 ]
then
    echo "[-] MOUNT ERROR! Aborting..."
    exit 42
fi

echo "Copy files:"
wget -O "/tmp/team-${CERT_ID}.p12" "${BASE_URL}${CERT_ID}"
FILES_TO_COPY="${FILES_TO_COPY} /tmp/team-${CERT_ID}.p12"

for i in $FILES_TO_COPY
do
    cp -v "${i}" "${MOUNT_DIR}"
done
sync

echo "Done!"
echo "Umounting"
umount "${MOUNT_DIR}"

echo "[+]Verify..."
mount "${DEVICE_PATH}" "${MOUNT_DIR}"

for i in $FILES_TO_COPY
do
    SHA_1=$(sha512sum "${i}"| awk '{ print $1 }')
    j=$(echo -n "${i}" |sed 's/.*\///g')
    SHA_2=$(sha512sum "${MOUNT_DIR}/${j}"| awk '{ print $1 }')
    if [ "${SHA_1}" != "" ] && [ "${SHA_1}" = "${SHA_2}" ]
    then
        echo "File \"${j}\" ok!"
    else
        echo "[-] -------------------- File \"${j}\" KO!"
        echo "We CANNOT continue, umouting & exiting :("
        umount "${MOUNT_DIR}"
        exit 42
    fi
done

echo "[+]Exiting..."
umount "${MOUNT_DIR}"
/bin/echo -e "${COUNT2}/${KEY_BY_TEAM} keys done for \e[32;01m${CERT_ID:0:5}\e[00m"
if [ $COUNT2 -ge "${KEY_BY_TEAM}" ]
then
    rm $COUNT2_FILE
    echo -n $(( $COUNT + 1 )) > "${COUNT1_FILE}"
else
    echo -n $(( $COUNT2 + 1 )) > "${COUNT2_FILE}"
fi
echo "Done, bye (:"
echo ""
echo ""
