#!/bin/bash

# load common variables and functions
source /bin/rae-generic-recovery

CONTAG=$1
REPO=devices/${CONTAG%:*}
TAG=${CONTAG#*:}
DELETE_DATA=$2
DELETE_CERTS=$3

echo "Begin recovery!"
beep -f 300.7 -r 2 -d 100 -l 400

echo "Prepare recovery environment!"
mount -o remount,rw /
umount ${LIVE_DIR} 
umount ${CERTS_DIR}
rm -rf ${LIVE_DIR} ${CERTS_DIR}
echo "Recovery environment ready!"

#remove container named rae-snapshot
echo "Remove existing rae-snapshot"
docker rm -f rae-snapshot 2> /dev/null

#get major version of target image
MAJOR_VERSION=$(echo $TAG | awk -F. '{print $1}')

#check if another image with the same major version exists locally
BASE_FOUND=$(docker images --format "{{.Tag}}" | awk -F. '{print $1}' | awk "/$MAJOR_VERSION/")

#if the base is not found then drop all images
if [ -z $BASE_FOUND ]; then

  echo "Base image $base_image not found"
  echo "Removing all images. Please wait"

  post_info_msg "Base image $CONTAG not found. Removing all local docker images"

  rae-itx-lcd 1= "Preparing" 2= "image repository"
  docker rmi -f $(docker images -a -q) 2> /dev/null
  docker system prune -a -f 2> /dev/null
  beep -f 2093  -l 200 -r 6
  rae-itx-lcd 1= "Image repository" 2= "ready"
  sleep 2
fi

echo "Mount live image partition!"
mkdir -p ${LIVE_DIR}
mount UUID=${ROOTFS_UUID} ${LIVE_DIR}
echo "Live image partition mounted!"

echo "Installing image : $REPO:$TAG"

#check if we have an update for this tag
post_info_msg "Downloading image $REPO:$TAG"
docker pull $REPO:$TAG >/dev/tty1 &
DOCKERPID=$!
TIMER=1

while ps -p $DOCKERPID >/dev/null
do
    DOTS=$((TIMER % 3))
    DCHAR='.'
    case $DOTS in
      1)
        DCHAR='.'
      ;;
      2)
        DCHAR='..'
      ;;
      0)
        DCHAR='...'
      ;;
    esac

    rae-itx-lcd 1= "Downloading $DCHAR" 2= "ver $TAG"
    sleep 1
    TIMER=$((TIMER+1))
done

post_info_msg "Image download completed : $REPO:$TAG"

#launch a new container using its tag and get its id
ID=$(docker run --name=rae-snapshot -id $REPO:$TAG /bin/bash)
MOUNTPT=`findmnt -t overlay -o TARGET | tail -n +2`
echo "Container ID $ID"

#check if ID is empty just error here
if [ -z "$MOUNTPT" ]; then
  echo "Image $TAG not found"
  post_error_msg "Image $CONTAG not found"
  rae-itx-lcd 1= "Image $TAG" 2= "not found!"
  beep -f 2093  -l 200 -r 6
  mount UUID=${DATA_UUID} ${DATA_DIR}
  rm -rf ${DATA_DIR}reset.rae
  umount UUID=${DATA_UUID}

  sleep 2
  reboot
fi

#rsync container snapshot to rootfs
echo "Syncing ${MOUNTPT} to ${LIVE_DIR}"

rae-itx-lcd 1= "Preparing image" 2= "Please wait"

rm -rf ${LIVE_DIR}*

post_info_msg "Installing image : $CONTAG"

rsync -aP --delete-before --info=progress2 --no-i-r --info=name0 ${MOUNTPT}/ ${LIVE_DIR} | awk -v CTAG="\"ver $TAG \"" -v RS='\r' '/%/ && (NR % 300 == 0) {system("rae-itx-lcd 1= \"Installing Image\" 2= " CTAG $2)}'

post_info_msg "Image installed $CONTAG"

#remove container rae-snapshot
echo "Remove temporary container :"
docker rm -f rae-snapshot

if [[ $DELETE_CERTS = "true" ]]; then
    echo "Mount certs partition!"
    mkdir -p ${CERTS_DIR}
    mount UUID=${CERTS_UUID} ${CERTS_DIR}
    echo "Certs partition mounted!"
    rm -rf ${CERTS_DIR}/*
    echo "[`date`] Deleted certificates from certs partition" | tee -a /var/log/rae-reset.log
    post_info_msg "[`date`] Deleted certificates from certs partition"
fi

if [[ $DELETE_DATA = "true" ]]; then
    echo "Mount data partition!"
    mkdir -p ${DATA_DIR}
    mount UUID=${DATA_UUID} ${DATA_DIR}
    echo "Data partition mounted!"
    rm -rf ${DATA_DIR}/*
    echo "[`date`] Removed all files in /data directory" | tee -a /var/log/rae-reset.log
    post_info_msg "[`date`] Removed all files in /data directory"
fi

#add dns server
echo "nameserver 8.8.8.8" > ${LIVE_DIR}etc/resolv.conf

#add localhost mapping
echo "127.0.0.1 localhost" > ${LIVE_DIR}etc/hosts

sync

echo "Unmount certs, rootfs and data partitions"
umount UUID=${ROOTFS_UUID}
umount UUID=${CERTS_UUID}
umount UUID=${DATA_UUID}
echo "Certs, rootfs and data partitions unmounted"

# remove reset file on successful sync
echo "version=$CONTAG" > /etc/reset-version
mount UUID=${DATA_UUID} ${DATA_DIR}
rm -rf ${DATA_DIR}reset.rae
rm -rf ${DATA_DIR}recovery.env
umount UUID=${DATA_UUID}

echo 'Installation complete!'
rae-itx-lcd 1= "Installation" 2= "complete"
beep -f 2093  -l 200 -r 6
sleep 2

echo "Current Image : $REPO:$TAG"
rae-itx-lcd 1= "Rebooting" 2= " "
echo "Rebooting! Please wait"
beep -f 1000 -r 2 -n -r 5 -l 10 --new
sleep 2
post_info_msg "Installation complete. Current image : $CONTAG"

rae-itx-lcd

reboot
