# Test that we can upgrade to the latest image version and roll back to the
# original version. Test will be skipped the testbed does not offer reboot
# (needs autopkgtest with a supporting runner).

test() {
    can_reboot || { echo "SKIP: cannot reboot testbed"; return; }

    # debug
    version_info    
    boot_info

    if after_reboot; then
        # second reboot: after rollback
        if [ -e "${ADT_ARTIFACTS}/rolled_back" ]; then
            orig_current=$(cat "${ADT_ARTIFACTS}/current")
            [ "$orig_current" = "$current" ] || fail "did not roll back to version $orig_current ($all_versions)"
            return
        fi

        # first reboot: after upgrade
        orig_avail=$(cat "${ADT_ARTIFACTS}/avail")
        [ "$orig_avail" = "$current" ] || fail "did not upgrade to current version $orig_avail != $current ($all_versions)"

        echo "rolling back..."
        sudo snappy rollback ubuntu-core
        touch "${ADT_ARTIFACTS}/rolled_back"
        reboot
        return
    fi

    # fake new available version by doing a current--
    switch_channel "s/build_number: $current/build_number: $((current-1))/"

    # we should have something now :)
    version_info
    
    [ $avail -gt $current ] || fail "$avail is not newer than $current"

    # save version for post-upgrade test
    save_version_info $avail $current    

    echo "upgrading..."
    sudo snappy update
    reboot
}
