#!/bin/sh
# Put the exported site content onto this server, over whatever is there (a fresh seeded install, usually).
#
#   cd thinkera.academy && sh ../deploy/import-site.sh /path/to/_export/2026-09-20
set -e

# Git Bash on Windows rewrites a container path like /app/media into a path on the C: drive
# before docker ever sees it. Linux has no such habit, so this is harmless on the server.
MSYS_NO_PATHCONV=1
export MSYS_NO_PATHCONV

# A value from .env. Windows line endings travel with the file, and a trailing carriage return turns
# «moodle» into a name Postgres has never heard of, so it is stripped here once.
envval() {
    grep "^$1=" .env | head -1 | cut -d= -f2- | tr -d '\015'
}

src=$1
[ -d "$src" ] || { echo "usage: sh import-site.sh <folder with site-db.dump and site-media.tgz>"; exit 1; }
[ -f .env ] || { echo "run this from thinkera.academy"; exit 1; }

db_user=$(envval POSTGRES_USER)
db_name=$(envval POSTGRES_DB)

echo "This replaces the CMS database «$db_name» and its uploaded images on THIS machine."
printf 'type yes to go on: '
read answer
[ "$answer" = "yes" ] || exit 1

docker compose stop web 2>/dev/null || true
docker compose up -d db
sleep 5

echo "database …"
docker compose exec -T db psql -U "$db_user" -d "$db_name" -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public;'
docker compose exec -T db pg_restore -U "$db_user" -d "$db_name" --no-owner --no-privileges < "$src/site-db.dump"

echo "media …"
docker compose run --rm -T --no-deps -v "$(cd "$src" && pwd):/backup:ro" web sh -c \
  'rm -rf /app/media/* 2>/dev/null; tar xzf /backup/site-media.tgz -C /app/media'

# The pages are compiled into the image, so a change to them reaches the server only through a rebuild.
echo "building …"
docker compose build web

echo "starting …"
docker compose up -d
sleep 8

# the addresses that differ between a laptop and a server come from .env, not from the content
echo
grep -E '^(SITE_URL|PLATFORM_URL)=' .env || true
echo "done. Open the site and check the header's «دخول المنصة» link."
