#!/bin/bash
#
# Build a sample symlink tree in ./symtree, then create target symlinks:
# - root : symlink to symtree itself.
# - loop : symlink that points to itself.
# - long : symlink chain of configurable depth.

set -eu

# Abort if symtree already exists.
if test -e symtree; then
    printf 'Error: symtree exists, aborting.\n' >&2
    exit 1
fi

# Step 1: Build base tree.
mkdir -p symtree/a/b symtree/x

# Create a real file.
printf 'Change return success. Going and coming without error. Action brings good fortune.\n' > symtree/a/b/file.txt

# Create some useful symlinks inside the tree.
ln -s ../file.txt symtree/a/b/link_to_file
ln -s ../b symtree/a/b/link_to_dir
ln -s /etc/hosts symtree/x/ext

# Step 2: create target symlinks in symtree root:
#  - root -> .
#  - loop -> loop.
#  - long -> deep chain
ln -s . symtree/root
ln -s loop symtree/loop

DEPTH=128
i=1
prev='a/b/file.txt'
while [ "$i" -le "$DEPTH" ]; do
    ln -s "$prev" symtree/chain.$i
    prev="chain.$i"
    i=$((i + 1))
done
ln -s "$prev" symtree/long

printf 'Done: created symtree with a %d-level chain.\n' "$DEPTH"
