#!/bin/bash

HSM_ROOT=/tmp/hsm_root
SLEEP=${SLEEP:-5}
file=/mnt/lustre/f0

get_times() {
    echo $(date +%s): $(stat -c "%X %Y %Z" $file 2> /dev/null) >&2
}

log() {
    get_times
    echo "# $@"
    $@
    get_times
}

mount_clients() {
    mount $HOSTNAME@tcp:/lustre /mnt/lustre -t lustre -o user_xattr,flock
    mount $HOSTNAME@tcp:/lustre /mnt/lustre2 -t lustre -o user_xattr,flock
    mount $HOSTNAME@tcp:/lustre /mnt/lustre-hsm -t lustre -o user_xattr,flock
    lhsmtool_posix -vvvv --hsm_root=$HSM_ROOT --bandwidth 1 --daemon /mnt/lustre-hsm &> /tmp/hsm.log
}

unmount_clients() {
    killall lhsmtool_posix
    umount /mnt/lustre
    umount /mnt/lustre2
    umount /mnt/lustre-hsm
}

remount_clients() {
    unmount_clients && mount_clients
}

hsm_state() {
    lfs hsm_state $1 | sed -r 's/^[^:]+: \(0x[[:xdigit:]]+\) *//'
}

rm -f $file
remount_clients

log sys_creat $file
sleep $SLEEP

log dd if=/dev/zero of=$file bs=1M count=10 conv=fsync status=noxfer
sleep $SLEEP

log dd if=$file of=/dev/null bs=1M count=10 status=noxfer
sleep $SLEEP

log dd if=/dev/zero of=$file bs=1M count=1 conv=fsync,notrunc status=noxfer
sleep $SLEEP

log remount_clients
sleep $SLEEP

log lfs hsm_archive $file
while [ "$(hsm_state $file)" != "exists archived" ]; do
    sleep 1
done
get_times
sleep $SLEEP

log lfs hsm_release $file
sleep $SLEEP

log remount_clients
