#!/bin/sh

#rsync -acv rok@192.168.113.43:/home/rok/Head/Builder/aetos/nesis /
#pkill nesis
#tail -f /tmp/log.txt

#ssh rok@192.168.113.43 'echo ' $(< ~/.ssh/id_rsa.pub) ' >> ~/.ssh/authorized_keys'

#scp rok@192.168.112.134:/home/rok/Head/Builder/nesis/nesis/nesis /root
#mv /root/nesis /nesis
#pkill nesis

#mount /dev/mmcblk0p1 /boot/ && scp rok@192.168.113.43:/home/rok/Head/Builder/aetos/boot/uInitramfs /boot/ && umount /boot && reboot
#mount /dev/mmcblk0p1 /boot/ && rsync -acv rok@192.168.113.43:/home/rok/Head/Builder/aetos/boot / && umount /boot && reboot

if ! [ -f "/root/.ssh/id_ed25519" ]; then
	ssh-keygen -f /root/.ssh/id_ed25519 -q -N ""
	cat /root/.ssh/id_ed25519.pub
fi

HOST=$1
if [ -e $HOST ]; then
	HOST="192.168.113.43:8000"
fi

CONFIG="/etc/fw_env.config"
MMC="/dev/mmcblk0"
OFFSET_B=6
OFFSET=9
fw_printenv > /dev/null 2>&1
if ! [ $? == 0 ]; then
	CONFIG="/etc/fw_env.config.spi"
	MMC="/dev/mmcblk1"
	OFFSET=3
	OFFSET_B=1
fi

STATE=$(fw_printenv -c $CONFIG boot-state -n)
if [ $STATE == "normal" ]; then
	ACTIVE=$(fw_printenv -c $CONFIG boot-active -n)
	PART="${MMC}p$(( ($ACTIVE^1)+$OFFSET ))"
	PART_BOOT="${MMC}p$(( ($ACTIVE^1)+$OFFSET_B ))"
	echo "Updating to $PART_BOOT:$PART"
	#ssh $HOST 'dd if=/home/rok/Branch/NavSync/Builder/HW_A20_/IMAGE_/root.squashfs' | dd of=$PART bs=128k conv=fsync
	rm -f /tmp/root.squashfs
	rm -f /tmp/boot.squashfs
	curl "$HOST/root.squashfs" -o /tmp/root.squashfs || exit
	dd if=/tmp/root.squashfs of=$PART bs=512k conv=fsync
	curl "$HOST/boot.squashfs" -o /tmp/boot.squashfs || exit
	dd if=/tmp/boot.squashfs of=$PART_BOOT bs=512k conv=fsync

	fw_setenv -c $CONFIG boot-active $((ACTIVE^1))
	fw_setenv -c $CONFIG boot-state once
	echo "Set active $(fw_printenv -c $CONFIG boot-active -n)"
fi

#sleep 2
#reboot
