1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3#
4# Run filesystem operations tests on an 1 MiB disk image that is formatted with
5# a vfat filesystem and mounted in a temporary directory using a loop device.
6#
7# Copyright 2022 Red Hat Inc.
8# Author: Javier Martinez Canillas <javierm@redhat.com>
9
10set -e
11set -u
12set -o pipefail
13
14BASE_DIR="$(dirname $0)"
15TMP_DIR="$(mktemp -d /tmp/fat_tests_tmp.XXXXXX)"
16IMG_PATH="${TMP_DIR}/fat.img"
17MNT_PATH="${TMP_DIR}/mnt"
18
19cleanup()
20{
21    mountpoint -q "${MNT_PATH}" && unmount_image
22    rm -rf "${TMP_DIR}"
23}
24trap cleanup SIGINT SIGTERM EXIT
25
26create_loopback()
27{
28    touch "${IMG_PATH}"
29    chattr +C "${IMG_PATH}" >/dev/null 2>&1 || true
30
31    truncate -s 1M "${IMG_PATH}"
32    mkfs.vfat "${IMG_PATH}" >/dev/null 2>&1
33}
34
35mount_image()
36{
37    mkdir -p "${MNT_PATH}"
38    sudo mount -o loop "${IMG_PATH}" "${MNT_PATH}"
39}
40
41rename_exchange_test()
42{
43    local rename_exchange="${BASE_DIR}/rename_exchange"
44    local old_path="${MNT_PATH}/old_file"
45    local new_path="${MNT_PATH}/new_file"
46
47    echo old | sudo tee "${old_path}" >/dev/null 2>&1
48    echo new | sudo tee "${new_path}" >/dev/null 2>&1
49    sudo "${rename_exchange}" "${old_path}" "${new_path}" >/dev/null 2>&1
50    sudo sync -f "${MNT_PATH}"
51    grep new "${old_path}" >/dev/null 2>&1
52    grep old "${new_path}" >/dev/null 2>&1
53}
54
55rename_exchange_subdir_test()
56{
57    local rename_exchange="${BASE_DIR}/rename_exchange"
58    local dir_path="${MNT_PATH}/subdir"
59    local old_path="${MNT_PATH}/old_file"
60    local new_path="${dir_path}/new_file"
61
62    sudo mkdir -p "${dir_path}"
63    echo old | sudo tee "${old_path}" >/dev/null 2>&1
64    echo new | sudo tee "${new_path}" >/dev/null 2>&1
65    sudo "${rename_exchange}" "${old_path}" "${new_path}" >/dev/null 2>&1
66    sudo sync -f "${MNT_PATH}"
67    grep new "${old_path}" >/dev/null 2>&1
68    grep old "${new_path}" >/dev/null 2>&1
69}
70
71unmount_image()
72{
73    sudo umount "${MNT_PATH}" &> /dev/null
74}
75
76create_loopback
77mount_image
78rename_exchange_test
79rename_exchange_subdir_test
80unmount_image
81
82exit 0
83