#!/bin/bash

STATE_FILE="/var/opt/nyquist/update-state/update-in-progress"
INCOMING_DIR="/opt/bogen/incoming"

if [[ -f "$STATE_FILE" ]]; then
    version=$(grep '^version=' "$STATE_FILE" | cut -d'=' -f2)
    archive_file=$(grep '^archive_file=' "$STATE_FILE" | cut -d'=' -f2)
    archive_name=$(basename "$archive_file")
    incoming_archive="$INCOMING_DIR/$archive_name"

    echo "Update version $version was interrupted and will be reinstalled."

    if [[ -f "$archive_file" ]]; then
        mv "$archive_file" "$INCOMING_DIR/"
        echo "Moved archive to $INCOMING_DIR"
    else
        echo "Warning: archive file not found at $archive_file"
        exit 1
    fi

    if [[ -f "$incoming_archive" ]]; then
        echo "Archive file in incoming, ready to re-install"

        /opt/bogen/nyq_update "$incoming_archive"
    else
        echo "Error: archive was not found in incoming after move"
        exit 1
    fi
fi