#!/bin/sh

set -e

TMP_DIR="$AUTOPKGTEST_TMP"
TARGET_DIR="target_dir"
cd "$TMP_DIR"

# Test for valid symbolic link
mkdir "$TARGET_DIR"
echo "test file content" > "$TARGET_DIR/target_file"
ln -s "$TARGET_DIR/target_file" valid_link

# ####################### TEST FOR EXISTING LINK #######################
OUTPUT=$(chase valid_link)
EXPECTED_OUTPUT=$(realpath "$TARGET_DIR/target_file")

if [ "$OUTPUT" != "$EXPECTED_OUTPUT" ]; then
  echo "Error: chase did not resolve the valid link correctly. Got: $OUTPUT, Expected: $EXPECTED_OUTPUT"
  exit 1
fi
echo "Test: Chase - Valid Symbolic Link Handling - Success"

# ####################### TEST FOR BROKEN LINK #######################
ln -s non_existent_file broken_link
OUTPUT_BROKEN=$(chase broken_link 2>&1 || true)
if echo "$OUTPUT_BROKEN" | grep -q "chase: .*: No such file or directory"; then
  :
else
  echo "Error: chase did not report error for broken link. Got: $OUTPUT_BROKEN"
  exit 1
fi
echo "Test: Chase - Broken Symbolic Link Handling - Success"

# ####################### TEST FOR MISSING LINK #######################
OUTPUT_MISSING=$(chase missing_link 2>&1 || true)
if echo "$OUTPUT_MISSING" | grep -q "chase: .*: No such file or directory"; then
  :
else
  echo "Error: chase did not report error for missing link. Got: $OUTPUT_MISSING"
  exit 1
fi
echo "Test: Chase - Missing Symbolic Link Handling - Success"

exit 0
