#!/bin/sh

declare cerbo_addr

if [ $# -eq 0 ]; then
  cerbo_addr=venus.local
else
  cerbo_addr=$1
fi

echo "Checking connection to the Victron Cerbo at address: $cerbo_addr"

my_os=$(uname)

if [[ "$my_os" == "Linux" ]] || [[ "$my_os" == "Darwin" ]]; then
  ping_comm="ping $cerbo_addr -c 3"
else
  ping_comm="ping $cerbo_addr -n 3"
fi

if ! $ping_comm; then
  echo "Cerbo at address $cerbo_addr is not available at the moment. Bye!"
  exit
fi

#Copy udev rules (to disable serial-starter and have a working RS485 converter)
scp -o IdentitiesOnly=yes lib/serial-starter.rules root@"$cerbo_addr":/etc/udev/rules.d/serial-starter.rules

#Copy nodered folder with libs and flows
scp -r -o IdentitiesOnly=yes lib/nodered root@"$cerbo_addr":/data/home/

#Permissions:
ssh -o IdentitiesOnly=yes root@"$cerbo_addr" chown -R nodered:nodered /data/home/nodered/

#Copy precompiled zerotier and rc.local 
scp -o IdentitiesOnly=yes -r lib/ZeroTierOne-1.6.4 root@"$cerbo_addr":/home/root
scp -o IdentitiesOnly=yes lib/rc.local root@"$cerbo_addr":/data
ssh -o IdentitiesOnly=yes root@"$cerbo_addr" chmod +x /data/rc.local

#Install Zerotier and reboot
ssh -o IdentitiesOnly=yes root@"$cerbo_addr" make install --directory=/home/root/ZeroTierOne-1.6.4
ssh -o IdentitiesOnly=yes root@"$cerbo_addr" reboot

echo "Waiting for the Cerbo to reboot (can take around a minute)..."
sleep 20

until ssh -o IdentitiesOnly=yes root@"$cerbo_addr" true >/dev/null 2>&1; do true ; done

source lib/cerbo_after_reboot.sh