#!/bin/bash
# -*- Mode: sh; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-
#
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: Michael Terry

# This script takes a directory and messes it up a bit, adding some random
# files with random data.

DIR="$1"
if [ "$#" -ne 1 ] || ! [ -d "$DIR" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

if [ ! -f "$DIR/.randomized" ] && [ -n "$(ls -A $DIR)" ]; then
  echo "Directory must be empty or previously randomized"
  exit 2
fi

touch "$DIR/.randomized"

# $RANDOM goes from 0 to 32k. With count, we go from 0 to 160M (160,000k)
modify_file() {
  dd if=/dev/urandom bs=$RANDOM count=5000 of="$1" 2>/dev/null
}

add_file() {
  filename="$(dd if=/dev/urandom bs=40 count=1 2>/dev/null | tr -d '\000/')"
  echo "Adding    $DIR/$filename"
  touch "$DIR/$filename"
  modify_file "$DIR/$filename"
}

numfiles() {
  ls -1 "$DIR" | wc -l
}

if [ "$(numfiles)" -gt 0 ]; then
  # For each existing file, a 1/3 chance of being either:
  # - deleted
  # - modified
  # - left alone
  for file in $DIR/*; do
    case $(( ( $RANDOM % 3) )) in
      0) echo "Deleting  $file"; rm "$file"; ;;
      1) echo "Modifying $file"; modify_file "$file"; ;;
      *) echo "Ignoring  $file"; ;;
    esac
  done
fi

# Now make sure there are at least 10 files, but no more than 100.
# And always add one file, for *some* kind of delta.

while [ "$(numfiles)" -lt 9 ]; do
  add_file
done
while [ "$(numfiles)" -gt 99 ]; do
  filename="$DIR/$(ls -1 \"$DIR\" | head -n1)"
  echo "Deleting  $filename"
  rm "$filename"
done

add_file
