#!/bin/bash

set -eu -o pipefail

if [[ ${EUID} -ne 0 ]]; then
    echo "This script should be run as root." > /dev/stderr
    exit 1
fi

if [[ $# -eq 0 ]]; then
    echo "No arguments supplied"
    exit 1
fi

if [[ "$1" == "--check" ]]; then
    echo "OK"
    exit 0
fi

target_dir="$1"
source_dir="$2"

source_stat=$(stat --format='%d,%i' "${source_dir}")
target_stat=$(stat --format='%d,%i' "${target_dir}")

# test sameness across bind mounts. if it's same, we can skip the emptiness check
if [[ "${source_stat}" == "${target_stat}" ]]; then
    echo "Source dir and target dir are the same"
    exit 0
fi

readonly test_file="${target_dir}/.chown-test"

mkdir -p "${target_dir}"
rm -f "${test_file}" # clean up any from previous run

if [[ -n $(ls -A "${target_dir}") ]]; then
    echo "volume dir is not empty"
    exit 2
fi

touch "${test_file}"
if ! chown yellowtent:yellowtent "${test_file}"; then
    echo "chown does not work"
    exit 3
fi
rm -f "${test_file}"
rm -r "${target_dir}" # will get recreated by the local storage addon

