#!/bin/sh

SDIR="$(dirname "$0")"

KERNELONLY=0

help()
{
    echo "-h: help"
    echo "-k KERNEL: update only kernel"
    echo "-s IP: board ip-address"
    echo "-c Don't copy config"
    exit
}

COPY_CONFIG=-c
while getopts hks:c flag
do
    case "${flag}" in
        h) help;;
        k) KERNELONLY=1;;
        s) BOARDIP=$OPTARG;;
        c) COPY_CONFIG=
    esac
done

echo Board-IP: $BOARDIP

if [ -z "$BOARDIP" ]
then
	BOARDIP=$(awk 'BEGIN{FS="="}/^ *BOARDIP/{gsub(" ", "", $2); gsub("\r", "", $2); gsub("\n", "", $2); print($2);}' $1)
fi
printf "BOARDIP: '%s'\n" "$BOARDIP"

if [ ! -f "/home/$USER/.ssh/id_rsa" ]
then
    mkdir -p "/home/$USER/.ssh"
    ssh root@"$BOARDIP" "exit"
    ssh-keygen -t rsa
fi

ssh-keygen -f "/home/$USER/.ssh/known_hosts" -R "$BOARDIP"
bash $SDIR/ssh-copy-id -i "/home/$USER/.ssh/id_rsa.pub" root@"$BOARDIP"

ssh root@"$BOARDIP" "if [ -f /etc/init.d/S60prtsoft ]; then /etc/init.d/S60prtsoft stop; else /etc/init.d/S39prtsoft stop; fi"
ssh root@"$BOARDIP" "if [ -f /etc/init.d/S59cvboot ]; then /etc/init.d/S59cvboot stop; else /etc/init.d/S38cvboot stop; fi"
ssh root@"$BOARDIP" "rmmod KM_CvKernelAccess"

if [ -f images/deploy.tgz ]; then
    scp images/deploy.tgz root@$BOARDIP:/tmp/
fi
if [ -f ./deploy.tgz ]; then
    scp ./deploy.tgz root@$BOARDIP:/tmp/
fi

if [ "$KERNELONLY" -eq "1" ]; then
    ssh root@"$BOARDIP" "cd /tmp; tar xvfz deploy.tgz; cd deploy; ./update.sh $COPY_CONFIG -k" 2>&1 | tee updlog.txt
else
    ssh root@"$BOARDIP" "cd /tmp; tar xvfz deploy.tgz; cd deploy; ./update.sh $COPY_CONFIG" 2>&1 | tee updlog.txt
fi

echo "You'll find a log in this dir in file updlog.txt"
