#!/bin/bash

scopeid=$1
if [ "$scopeid" ]
then
 echo ""
 echo "Uninstalling and Purging existing DPS subscription"
 su -c "iotedge system stop"
 su -c "docker system prune -a -f"
 su -c "apt-get remove --purge -y aziot-identity-service aziot-edge"
 su -c "rm /run/aziot/*.sock"
 su -c "dpkg -i /home/newboot/Azure-Setup/aziot-identity-service_1.2.6-1_amd64.deb"
 su -c "dpkg -i /home/newboot/Azure-Setup/aziot-edge_1.2.10-1_amd64.deb"

 echo ""
 echo "Provisioning with ScopeID : $scopeid"
 echo ""
 cp /home/newboot/Azure-Setup/template/config.toml.template config.toml
 sed -i "s/_SCOPE_ID/$scopeid/g" config.toml
 tpm=$(echo \n | su -c /home/newboot/Azure-Setup/scripts/./tpm_device_provision | grep Registration -A1 | tail -n1 | sed 's/\r//')
 sed -i "s/_REG_ID/$tpm/" config.toml
 su -c "mv config.toml /etc/aziot/config.toml"
 
echo ""
 echo "Running iotedge config apply"
 echo ""
 iotedge config apply
else
 echo 'Usage: ./dps-migrate SCOPEID (run as sudoer)'
 echo 'Please add the azure DPS scopeId'
 exit 1
fi
