#
# simple-pts.sh - basic set of production tests for DI/OT System Board
# 
# Author: Greg Daniluk
# Copyright CERN 2021
# 

#!/bin/bash

export FDISK_CMD="/usr/bin/fdisk.cmd"
export LOGFILE="/tmp/simple-pts.log"
export TEST_IP=$(/sbin/ip route | awk '/default/ { print $3 }')

echo "--------------------------------" | tee $LOGFILE
echo "Checking sensors..." | tee -a $LOGFILE
echo "---------------------------------" | tee -a $LOGFILE
diot_util -e pts | tee -a $LOGFILE 2>&1

echo "---------------------------------" | tee -a $LOGFILE
echo -n "Checking network interface..."
echo "Checking network interface..." >> $LOGFILE
ping -c 5 $TEST_IP >> $LOGFILE && echo "OK." || echo "Error."

echo "---------------------------------" | tee -a $LOGFILE
echo "QSPI and eMMC..." | tee -a $LOGFILE
echo "" | tee -a $LOGFILE

echo -n "Erase QSPI..."
echo "Erase QSPI..." >> $LOGFILE
flash_erase /dev/mtd0 0 0 >> $LOGFILE 2>&1 && echo "OK." || { echo "Error."; exit 1; }

echo -n "Copy BOOT.bin to QSPI..."
echo "Copy BOOT.bin to QSPI..." >> $LOGFILE
cat /run/media/mmcblk1p1/BOOT.bin > /dev/mtd0 && echo "OK." || echo "Error."


umount /run/media/mmcblk0* 2> /dev/null

echo -n "Creating eMMC partitions..."
echo "Creating eMMC partitions..." >> $LOGFILE
cat $FDISK_CMD | fdisk /dev/mmcblk0 >> $LOGFILE 2>&1 && echo "OK." || { echo "Error."; exit 1; }
sleep 1

echo -n "Formatting eMMC partition 1..."
echo "Formatting eMMC partition 1..." >> $LOGFILE
umount /run/media/mmcblk0p1 >> $LOGFILE
mkfs.vfat /dev/mmcblk0p1 >> $LOGFILE && echo "OK." || { echo "Error."; exit 1; }

echo -n "Formatting eMMC partition 2..."
echo "Formatting eMMC partition 2..." >> $LOGFILE
umount /run/media/mmcblk0p2 >> $LOGFILE 2>&1
mkfs.ext4 -F /dev/mmcblk0p2 >> $LOGFILE 2>&1 && echo "OK." || { echo "Error."; exit 1; }

echo -n "Mounting eMMC partitions..."
echo "Mounting eMMC partitions..." >> $LOGFILE
mount /dev/mmcblk0p1 /run/media/mmcblk0p1 >> $LOGFILE 2>&1 || { echo "Error."; exit 1; }
mount /dev/mmcblk0p2 /run/media/mmcblk0p2 >> $LOGFILE 2>&1 && echo "OK." || { echo "Error."; exit 1; }

echo -n "Copying image.ub to eMMC..."
echo "Copying image.ub to eMMC..." >> $LOGFILE
cp /run/media/mmcblk1p1/image.ub /run/media/mmcblk0p1 >> $LOGFILE 2>&1 || { echo "Error."; exit 1; }
sync
echo "OK."

echo -n "Copying SSH keys to eMMC..."
echo "Copying SSH keys to eMMC..." >> $LOGFILE
mkdir -p /run/media/mmcblk0p2/diot/etc/dropbear >> $LOGFILE 2>&1 || { echo "Error."; exit 1; }
cp /etc/dropbear/dropbear_rsa_host_key /run/media/mmcblk0p2/diot/etc/dropbear/ >> $LOGFILE 2>&1 || { echo "Error."; exit 1; }
sync
echo "OK."

echo -n "Copying logfile to eMMC..."
mkdir -p /run/media/mmcblk0p2/pts
cp $LOGFILE /run/media/mmcblk0p2/pts/ && echo "OK." || echo "Error."

echo "---------------------------------" | tee -a $LOGFILE
echo "Everything done"
