#!/bin/bash

modem_mr=$(mmcli -L | grep -oP 'Modem\/\K\d+' | head -1)
locked=$(mmcli -m $modem_mr --command="AT+GTFCCLOCKSTATE")
    if [ "$locked" == "1" ]; then
        echo "Modem is already unlocked. Exiting."
        exit 0
    fi
challenge=$(mmcli -m $modem_mr --command="AT+GTFCCLOCKGEN" | grep -o "0x[0-9a-fA-F]*" | sed "s/'//g")
to_hash=$(printf "%x" "$challenge")
to_hash=$(($to_hash + 0xbb23be7f))
res=$(echo -n "$to_hash" | sha256sum | cut -c1-8)
res=$(printf "%d" "0x$res")
mmcli -m $modem_mr --command="AT+GTFCCLOCKVER=$res"
mmcli -m $modem_mr --command="AT+GTFCCLOCKMODEUNLOCK"
mmcli -m $modem_mr --command="AT+CFUN=1"
locked=$(mmcli -m $modem_mr --command="AT+GTFCCLOCKSTATE")
    if [ "$locked" == "1" ]; then
        echo "Modem is succesfull unlocked. Exiting."
        exit 0
    fi
exit 1
