#!/bin/bash
# -*- Mode: sh; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-
#
# This file is part of Déjà Dup.
# For copyright information, see AUTHORS.
#
# Déjà Dup is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Déjà Dup is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Déjà Dup.  If not, see <http://www.gnu.org/licenses/>.

# 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
modify_file() {
  dd if=/dev/urandom bs=$RANDOM count=1 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
