#!/bin/bash
#
# hardware-sync-200 - update changed hardware data while machine is deployed
#
# --- Start MAAS 1.0 script metadata ---
# name: hardware-sync-200
# title: Update hardware changes
# description: Run maas-run-scripts to update hardware changes
# script_type: testing
# hardware_type: node
# parallel: instance
# --- End MAAS 1.0 script metadata ---

# Collect region controller URL from /etc/cloud/cloud.cfg.d/91_kernel_cmdline_url.cfg
METADATA_URL=$(awk '/metadata_url:/ {print $2}' /etc/cloud/cloud.cfg.d/91_kernel_cmdline_url.cfg | tr -d '"'\''\r')

# Strip /metadata endpoint on METADATA_URL and prepare correct endpoint
SCRIPT_URL="${METADATA_URL%/metadata/}/maas-run-scripts"

# Path from where MAAS credentials will be pulled for maas-run-scripts
CLOUD_CFG="/etc/cloud/cloud.cfg.d/91_kernel_cmdline_url.cfg"

# Create new file to run maas-run-scripts when status is changed from Testing to Deployed
cat << EOF > /tmp/hw_sync
# Make poweroff and reboot unusable to not poweroff or reboot machine until script is finished
systemctl mask poweroff.target reboot.target halt.target
# Wait 30s to proceed further
sleep 30
# Download maas-run-scripts from region controller
/usr/bin/wget -O /usr/bin/maas-run-scripts $SCRIPT_URL
# Make it executable
/bin/chmod 0755 /usr/bin/maas-run-scripts 
# Run maas-run-scripts with config from cloud-init files
/usr/bin/maas-run-scripts report-results --config $CLOUD_CFG
# Make poweroff and reboot usable again
systemctl unmask poweroff.target reboot.target halt.target
# Force poweroff
systemctl poweroff -f 
EOF

# Make this script executable
chmod +x /tmp/hw_sync 
# Run script in the background
nohup /tmp/hw_sync > /tmp/hw_sync.log 2>&1 & 
# Finish hardware-sync-200 script to change status machine status from Testing to Deployed
exit 0
