#!/bin/bash
# Multiplic cPanel Deployment Scaffold
# Usage: bash infra/cpanel/deploy.sh

set -e

ARTIFACT_DIR="deploy_artifacts"
CONFIG_FILE="multiplic.json"

# Check for multiplic.json
if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: $CONFIG_FILE not found."
    exit 1
fi

mkdir -p "$ARTIFACT_DIR"

# Iterate through sites in multiplic.json
# Using jq to parse sites. This assumes a structure like:
# { "sites": [ { "name": "aiistech", "path": "sites/aiistech" } ] }

SITES=$(jq -c '.sites[]' "$CONFIG_FILE")

for SITE in $SITES; do
    NAME=$(echo "$SITE" | jq -r '.name')
    DIR=$(echo "$SITE" | jq -r '.path')
    
    echo "Building site: $NAME in $DIR"
    
    pushd "$DIR" > /dev/null
    
    # Perform build
    npm install
    npm run build
    
    # Prepare artifact
    TMP_DIR="../../$ARTIFACT_DIR/$NAME"
    mkdir -p "$TMP_DIR"
    cp -r dist/* "$TMP_DIR/"
    
    # Inject cPanel specifics
    cp ../../infra/cpanel/proxy.php "$TMP_DIR/"
    cp ../../infra/cpanel/.htaccess.template "$TMP_DIR/.htaccess"
    
    # Zip it up
    cd "../../$ARTIFACT_DIR"
    zip -r "${NAME}_deploy.zip" "$NAME"
    rm -rf "$NAME"
    
    popd > /dev/null
    
    echo "Artifact created: $ARTIFACT_DIR/${NAME}_deploy.zip"
done

echo "Deployment scaffold complete."
