#!/bin/bash -e
# Prepare Dangerous Pi files for installation

# This script runs OUTSIDE the chroot environment
# It prepares files that will be copied into the image

echo "Preparing Dangerous Pi files..."

# Create temporary directory for files
mkdir -p "${ROOTFS_DIR}/tmp/dangerous-pi-files"

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Copy application structure from the files directory
cp -r "${SCRIPT_DIR}/files/app" "${ROOTFS_DIR}/tmp/dangerous-pi-files/"
cp -r "${SCRIPT_DIR}/files/systemd" "${ROOTFS_DIR}/tmp/dangerous-pi-files/"
cp -r "${SCRIPT_DIR}/files/scripts" "${ROOTFS_DIR}/tmp/dangerous-pi-files/"
cp -r "${SCRIPT_DIR}/files/etc" "${ROOTFS_DIR}/tmp/dangerous-pi-files/"
cp "${SCRIPT_DIR}/files/requirements.txt" "${ROOTFS_DIR}/tmp/dangerous-pi-files/"

# Create VERSION file
echo "0.1.0-$(date +%Y%m%d)" > "${ROOTFS_DIR}/tmp/dangerous-pi-files/VERSION"

# Create empty directories
mkdir -p "${ROOTFS_DIR}/tmp/dangerous-pi-files/data"
mkdir -p "${ROOTFS_DIR}/tmp/dangerous-pi-files/logs"

# Copy dt-design-system to /opt/ so frontend's file: dependency resolves
# Frontend package.json has: "@dangerousthings/web": "file:../../../dt-design-system/packages/web"
# From /opt/dangerous-pi/app/frontend/, ../../../ resolves to /opt/
if [ -d "${SCRIPT_DIR}/files/dt-design-system" ]; then
    echo "Copying dt-design-system for frontend dependency resolution..."
    mkdir -p "${ROOTFS_DIR}/opt/dt-design-system/packages"
    cp -r "${SCRIPT_DIR}/files/dt-design-system/packages/web" "${ROOTFS_DIR}/opt/dt-design-system/packages/"
    cp -r "${SCRIPT_DIR}/files/dt-design-system/packages/tokens" "${ROOTFS_DIR}/opt/dt-design-system/packages/"
    cp "${SCRIPT_DIR}/files/dt-design-system/package.json" "${ROOTFS_DIR}/opt/dt-design-system/"
fi

echo "Files prepared successfully"
