#!/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

# Use GNU tar explicitly (required for --exclude on Solaris/OmniOS)
if [ -x /usr/gnu/bin/tar ]; then
    TAR=/usr/gnu/bin/tar
else
    TAR=tar
fi

TARGET="/opt"
DATA_DIR="$TARGET/csweb-gui/data"
ZIP_URL="https://www.napp-it.org/doc/downloads/napp-it_cs_dev.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 while strictly excluding the 'perl' folder
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 --exclude='perl' -cf - .) | (cd "$TARGET" && $TAR -xf -)

# Force-remove any perl fragments in the target just in case
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
