#!/usr/bin/env bash
set -euo pipefail

# Run this from:
#   /var/www/app/pharmex_week_6
#
# Before running it, put the client's ten JPGs in:
#
#   client_test_adverts/no_rem/page_1.jpg ... page_5.jpg
#   client_test_adverts/with_rem/page_1.jpg ... page_5.jpg
#
# "no_rem"  = the versions with the small bottom disclaimer/safety text removed
# "with_rem" = the versions retaining that text

MEGAVIT_SOURCE="megavit-test"
CLIENT_STAGE="client_test_adverts"

NO_REM_DIR="$CLIENT_STAGE/no_rem"
WITH_REM_DIR="$CLIENT_STAGE/with_rem"

MEGAVIT_DEST="projects/megavit"
CLIENT_DEST="projects/client"

products=(
    "cardionova"
    "neuroviva"
    "calmora"
    "dermalux"
    "vitacharge"
)

echo "Checking client advert staging files..."

for i in 1 2 3 4 5; do
    if [ ! -f "$NO_REM_DIR/page_${i}.jpg" ]; then
        echo "ERROR: missing $NO_REM_DIR/page_${i}.jpg"
        exit 1
    fi

    if [ ! -f "$WITH_REM_DIR/page_${i}.jpg" ]; then
        echo "ERROR: missing $WITH_REM_DIR/page_${i}.jpg"
        exit 1
    fi
done

if [ ! -d "$MEGAVIT_SOURCE" ]; then
    echo "ERROR: $MEGAVIT_SOURCE does not exist."
    exit 1
fi

echo "Creating project directories..."

mkdir -p "$MEGAVIT_DEST/residual"
mkdir -p "$MEGAVIT_DEST/live_analyses_aside"

mkdir -p "$CLIENT_DEST/residual"
mkdir -p "$CLIENT_DEST/live_analyses_aside"

echo
echo "Moving existing MegaVit files into $MEGAVIT_DEST ..."

# Move ordinary top-level files.
find "$MEGAVIT_SOURCE" \
    -maxdepth 1 \
    -type f \
    -exec mv -v -t "$MEGAVIT_DEST" -- {} +

# Move residual files, preserving the residual directory.
if [ -d "$MEGAVIT_SOURCE/residual" ]; then
    find "$MEGAVIT_SOURCE/residual" \
        -maxdepth 1 \
        -type f \
        -exec mv -v -t "$MEGAVIT_DEST/residual" -- {} +
fi

# Move analyses previously put aside.
if [ -d "$MEGAVIT_SOURCE/live_analyses_aside" ]; then
    find "$MEGAVIT_SOURCE/live_analyses_aside" \
        -maxdepth 1 \
        -type f \
        -exec mv -v -t "$MEGAVIT_DEST/live_analyses_aside" -- {} +
fi

echo
echo "Moving and renaming client adverts into $CLIENT_DEST ..."

for i in 1 2 3 4 5; do
    product="${products[$((i - 1))]}"

    mv -v \
        "$NO_REM_DIR/page_${i}.jpg" \
        "$CLIENT_DEST/${product}_no_rem.jpg"

    mv -v \
        "$WITH_REM_DIR/page_${i}.jpg" \
        "$CLIENT_DEST/${product}_with_rem.jpg"
done

echo
echo "Removing now-empty staging directories where possible..."

rmdir "$MEGAVIT_SOURCE/residual" 2>/dev/null || true
rmdir "$MEGAVIT_SOURCE/live_analyses_aside" 2>/dev/null || true
rmdir "$MEGAVIT_SOURCE" 2>/dev/null || true

rmdir "$NO_REM_DIR" 2>/dev/null || true
rmdir "$WITH_REM_DIR" 2>/dev/null || true
rmdir "$CLIENT_STAGE" 2>/dev/null || true

echo
echo "=== Project-owned structure ==="
find projects -maxdepth 2 -type d | sort

echo
echo "=== MegaVit files ==="
find "$MEGAVIT_DEST" -maxdepth 2 -type f | sort

echo
echo "=== Client files ==="
find "$CLIENT_DEST" -maxdepth 2 -type f | sort

echo
echo "Migration complete."
