#!/bin/sh
# Ensure a standard path environment to find tools across different OS flavors
PATH=/usr/gnu/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin
export PATH

TARGET="/opt"
DATA_DIR="$TARGET/csweb-gui/data"
ZIP_URL="https://www.napp-it.org/doc/downloads/napp-it_cs.zip"
TEMP_ZIP="/tmp/napp-it_cs.zip"
EXTRACT_DIR="/tmp/csweb_extracted"

echo "=== Starting Universal POSIX Setup ==="

# 1. Rename old data directory instead of deleting it
if [ -d "$DATA_DIR" ]; then
    # Generate timestamp in YYYY_MM_DD_HH_Min format
    TIMESTAMP=$(date +"%Y_%m_%d_%H_%M")
    BACKUP_DIR="${DATA_DIR}_${TIMESTAMP}"

    echo "Backing up old data directory to: $BACKUP_DIR"
    mv "$DATA_DIR" "$BACKUP_DIR"
fi

# 2. Create target directory if it does not exist
mkdir -p "$TARGET"

# 3. Download the zip archive
echo "Downloading napp-it_cs.zip..."
curl -sL -o "$TEMP_ZIP" "$ZIP_URL"

# 4. Extract to a temporary directory
echo "Extracting archive..."
rm -rf "$EXTRACT_DIR"
mkdir -p "$EXTRACT_DIR"

# Fallback mechanism for zip extraction
if command -v unzip >/dev/null 2>&1; then
    unzip -q "$TEMP_ZIP" -d "$EXTRACT_DIR"
else
    echo "ERROR: unzip not found, cannot extract ZIP archive" >&2
    exit 1
fi

# 5. Copy contents, then remove the 'perl' folder afterward (see below).
# NOTE cs_26.08.10 fix: this used to pass --exclude='perl' to $TAR,
# preferring /usr/gnu/bin/tar (GNU tar) if present, plain "tar"
# otherwise. On systems without GNU tar installed (confirmed live on
# an OmniOS host: no /usr/gnu/bin/tar) that fallback silently used the
# native SVR4/illumos tar, which does NOT support GNU-style long
# options like --exclude -- it failed with "tar: X: unknown function
# modifier" on the FIRST tar in the pipe, producing an empty stream,
# so the second tar extracted nothing at all and csweb-gui ended up
# completely missing (later failing with "server.pl not found").
# Fix: drop --exclude entirely and rely solely on the post-copy
# "rm -rf $TARGET/perl" below (which was already present as a second,
# redundant safety net) -- plain "tar -cf -"/"tar -xf -" with no
# GNU-only flags works identically on every POSIX tar, including
# illumos/Solaris native tar, so no GNU-tar detection is needed at all.
echo "Copying data to $TARGET (excluding perl)..."
SRC_DIR="$EXTRACT_DIR"
if [ -d "$EXTRACT_DIR/opt" ]; then
    SRC_DIR="$EXTRACT_DIR/opt"
fi

(cd "$SRC_DIR" && tar -cf - .) | (cd "$TARGET" && tar -xf -)

# Remove perl fragments in the target (the only exclusion mechanism now)
rm -rf "$TARGET/perl"

# Cleanup temporary files
rm -f "$TEMP_ZIP"
rm -rf "$EXTRACT_DIR"

echo "=== Setup successfully completed! ==="

# Start csweb-gui
if [ -f "$TARGET/csweb-gui/start.pl" ]; then
    echo "Starting csweb-gui (start.pl 1)..."
    perl "$TARGET/csweb-gui/start.pl" 1
else
    echo "WARNING: start.pl not found, start manually: perl /opt/csweb-gui/start.pl 1"
fi
