#!/bin/bash

# x-terminal-emulator

cd "$(dirname "$0")"

export TEMP=/tmp/cvunpack
export IP_ADDR=$1
export FIRMWARE=$2

RetCode=0

mkdir -p $TEMP

echo ./cvunpack -t$TEMP $FIRMWARE
./cvunpack -t$TEMP "$FIRMWARE"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi

# ssh-keygen -f "/home/$USER/.ssh/known_hosts" -R "$IP_ADDR"
scp -r $TEMP/Y:/* root@$IP_ADDR:/tmp/
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi

ssh root@$IP_ADDR "/etc/init.d/S60prtsoft stop"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
ssh root@$IP_ADDR "chmod +x /tmp/deploy/*.sh; chmod +x /tmp/deploy/intern/*.sh; /tmp/deploy/update.sh -p"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
scp $TEMP/Y:/prtsoft.elf  root@$IP_ADDR:/mnt/inactive_rootfs/opt 
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
scp $TEMP/FPGA_IMG_ID.txt root@$IP_ADDR:/mnt/inactive_rootfs/
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
scp -r $TEMP/opt root@$IP_ADDR:/mnt/inactive_rootfs
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
scp -r $TEMP/usr root@$IP_ADDR:/mnt/inactive_rootfs
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
ssh root@$IP_ADDR "chmod +x /mnt/inactive_rootfs/opt/prtsoft.elf"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
ssh root@$IP_ADDR "chmod +x /mnt/inactive_rootfs/opt/dump_registers"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
ssh root@$IP_ADDR "chmod +x /mnt/inactive_rootfs/opt/fpga_io_interactive"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
ssh root@$IP_ADDR "chmod +x /mnt/inactive_rootfs/opt/fpga_load"
ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi

rm -rf $TEMP

if [ $RetCode -ne 0 ]; then
	read
fi
