#!/bin/sh

printf "\e[1;33mDG Studio\e[0m pre-configured image for Tinkerboard S \n\n"
printf "Provisioning from \e[1;32mdgman.dg-studio.eu\e[0m\nUse your regular DGMAN production credentials\n"
printf "Your credentials will not be stored on this device\n\n"

printf "In case of problems with logging in, use a web browser to go to \e[1;32mdgman.dg-studio.eu\e[0m and use the \"Forgot password\" feature. "
printf "Keep in mind that many failed login attempts will result in your account or IP address being locked out across all production services.\n\n"

rm -f pack.zip 2> /dev/null
rm -f pack 2> /dev/null

# leave whitespaces below the next line to allow automatic address replacement!
DGMAN_ADDRESS=https://dgman.dg-studio.eu/
                                                 

while [ ! -f pack.zip ]
do

	printf "E-mail address: "
	read USERNAME

	stty -echo
	printf "Password: "
	read PASSWORD
	stty echo


	printf "Preparing device identification\n"
	
	ip link show > ip.out

	printf "Attemting to download provisioning package \n"
	
	wget --no-verbose --timeout=10 --auth-no-challenge --user ${USERNAME} --password ${PASSWORD} --post-file=ip.out ${DGMAN_ADDRESS}api/provision/Armbian/20.11/pack.zip

	printf "Unzipping provisioning package...\n"

	unzip -o pack.zip -d pack > /dev/null

done

echo "$DGMAN_ADDRESS" > /dgs/firstrun/pack/DP_DGMAN_ADDR

echo "\nProvisioning done\n"

cd pack
if [ -f install.sh ]
then
	echo "\nInstallation script found. Starting installation.\n"
	chmod a+x install.sh
	./install.sh
fi
cd ..

rm pack.zip

printf "\n\e[1;33mHId\e[0m: \e[1;32m`cat pack/DP_ID`\e[0m\n"
printf "\e[1;33mVId\e[0m: \e[1;32m`cat pack/DP_VPN_ID`\e[0m\n"
printf "\e[1;33mDevice identity string\e[0m: \e[1;32m`cat pack/DP_IDENTITY_STRING`\e[0m\n"
printf "\e[1;33mAuthorized in\e[0m: \e[1;32m${DGMAN_ADDRESS}\e[0m\n"

sleep 5