#!/bin/sh 
#
#  remote.it Claimcode is for authorizing local access. The code is also sent in the 
#  Device ready message for app and portal based claiming
#
#  connectd_set_claimcode 
#
#  will alter contents in CONNECTD_DIR
#
#  remot3.it, Inc. : https://remote.it

BASEDIR=$CONNECTD_BASEDIR
CONNECTD_DIR="$BASEDIR"/etc/connectd
# pick up global options, e.g. PLATFORM and API
. "$CONNECTD_DIR"/oem_settings

if [ -f "/etc/connectd/hardware_id.txt" ]; then
    hwid=$(cat /etc/connectd/hardware_id.txt)
else 
    echo "Device not registered"
    exit
fi   

if [ "$1" = "get" ]; then

    if [ -f "/etc/connectd/claimcode.txt" ]; then
        cc=$(cat /etc/connectd/claimcode.txt)
        echo "last claimcode is $cc"
    fi
else 

    claimcode=$(awk -v min=10001 -v max=99999 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')

    if [ -f "/etc/connectd/hardware_id.txt" ]; then
        hwid=$(cat /etc/connectd/hardware_id.txt)
        echo $claimcode > /etc/connectd/claimcode.txt

        DIRECTORY=$(oemGetWebPath)
        if [ -d "$DIRECTORY" ]; then
            if [ ! -d "/var/www/html/r3/$hwid" ]; then
                sudo mkdir /var/www/html/r3/$hwid 
            fi
            echo '{"code":"'$claimcode'"}' > /var/www/html/r3/$hwid/claimcode.json
        fi
        echo $claimcode
    fi

fi
