#!/bin/bash

t="$*.inode64_$$"
tt="/dev/shm/$$t"
td="/dev/shm/$$td"

if [ ! -e "$*" ]; then
	echo "Not found: $*"
	exit 1
fi

if [ -d "$t" ]; then
	echo "$t exists"
	exit 1
fi

if [ -d "$tt" ]; then
	echo "$tt exists"
	exit 1
fi

if [ -d "$td" ]; then
	echo "$td exists"
	exit 1
fi

if [ $(stat -c %i -- "$*") -lt 4294967296 ]; then
	echo "Already 32-bit: $*"
	exit 0
fi

set -ex

if [ -d "$*" ]; then
	d=$(dirname -- "$*")
	touch --reference="$*" -- "$tt"
	touch --reference="$d" -- "$td"
	mv -f -- "$*" "$t"
	mkdir -m700 -- "$*"
	chown --reference="$t" -- "$*"
	chmod --reference="$t" -- "$*"
	(cd -- "$t" && find . -mindepth 1 -maxdepth 1 -print0 | xargs -r0 mv -ft "../$*" --)
	rmdir -- "$t"
	touch -h --reference="$tt" -- "$*"
	touch -h --reference="$td" -- "$d"
	rm -f "$tt" "$td"
elif [ -f "$*" ]; then
	d=$(dirname -- "$*")
	touch --reference="$d" -- "$td"
	cp -Pa -- "$*" "$t"
	# We can just clobber plain files
	mv -f -- "$t" "$*"
	touch -h --reference="$td" -- "$d"
	rm -f "$td"
else
	d=$(dirname -- "$*")
	touch --reference="$d" -- "$td"
	cp -Pa -- "$*" "$t"
	# For links and other weird files, we need to delete first
	rm -f -- "$*"
	mv -f -- "$t" "$*"
	touch -h --reference="$td" -- "$d"
	rm -f "$td"
fi
