#!/bin/bash

. config/options

echo "Device: "${DEVICE}
echo "IP: "${DEVICE_IP}
LOCAL_MEDIA="/media/portisch/COREELEC"

if [ ! -e "${LOCAL_MEDIA}" ]; then
  COREELEC_CMD="$(sshpass -p "coreelec" ssh root@${DEVICE_IP} 'cat /flash/config.ini' | grep "coreelec=.*toram.*")"
  if [ "$(echo "$COREELEC_CMD" | grep '#')" != "" ]; then
    echo "Please enable 'toram' first in config.ini!"
    exit
  fi
fi

# clean out stamp for rebuild package
while [ -n "${1}" ]; do
  PACKAGE="${PACKAGE:-${1}}"
  if [ "${PACKAGE}" != "" ]; then
    echo "Clean out stamp for package '${PACKAGE}'..."
    rm -f build.${DISTRO}-${DEVICE}.${ARCH}-${OS_MAJOR}/.stamps/${PACKAGE}/build_target

    if [ "${PACKAGE}" = "linux" ]; then
      BUILD_FOLDER=$(get_build_dir ${PACKAGE})
      PACKAGE_PATH="${BUILD_FOLDER}/arch/${TARGET_KERNEL_ARCH}/boot/${KERNEL_TARGET}"
      [ -f "${PACKAGE_PATH}" ] && rm -f "${PACKAGE_PATH}"
    fi
  fi
  shift
done

if ls target/*.kernel 1> /dev/null 2>&1; then
  rm -f target/*.kernel
fi

if ls target/*.system 1> /dev/null 2>&1; then
  rm -f target/*.system
fi

sleep 1

# build dirty system build
make system

KERNEL=$(ls target/*.kernel)
if [ -e "${LOCAL_MEDIA}" ]; then
  if [ -f "${KERNEL}" ]; then
    rm -rf ${LOCAL_MEDIA}/kernel.img
    cp -r ${KERNEL} ${LOCAL_MEDIA}/kernel.img
    sync
  fi
elif [ -f "${KERNEL}" ]; then
  echo "Copy ${KERNEL} to ${DEVICE_IP}"
  sshpass -p "coreelec" ssh root@${DEVICE_IP} 'mount -o remount,rw /flash'
  sshpass -p "coreelec" ssh root@${DEVICE_IP} '[ -f /flash/kernel.img ] && rm -f /flash/kernel.img'
  sshpass -p "coreelec" ssh root@${DEVICE_IP} 'sync'
  sshpass -p "coreelec" scp -r ${KERNEL} root@${DEVICE_IP}:/flash/kernel.img
fi

SYSTEM=$(ls target/*.system)
if [ -e "${LOCAL_MEDIA}" ]; then
  if [ -f "${SYSTEM}" ]; then
    rm -rf ${LOCAL_MEDIA}/SYSTEM
    cp -r ${SYSTEM} ${LOCAL_MEDIA}/SYSTEM
    sync
  fi
elif [ -f "${SYSTEM}" ]; then
  echo "Copy ${SYSTEM} to ${DEVICE_IP}"
  sshpass -p "coreelec" ssh root@${DEVICE_IP} 'mount -o remount,rw /flash'
  sshpass -p "coreelec" ssh root@${DEVICE_IP} '[ -f /flash/SYSTEM ] && rm -f /flash/SYSTEM'
  sshpass -p "coreelec" ssh root@${DEVICE_IP} 'sync'
  sshpass -p "coreelec" scp -r ${SYSTEM} root@${DEVICE_IP}:/flash/SYSTEM
fi

if [ ! -e "${LOCAL_MEDIA}" ] && [ -f "${KERNEL}" -o -f "${SYSTEM}" ]; then
  sshpass -p "coreelec" ssh root@${DEVICE_IP} 'sync'
  sshpass -p "coreelec" ssh root@${DEVICE_IP} 'reboot'
fi
