#!/bin/bash
#
# LetsBe Hub Production Setup Script
#
# Usage: ./setup.sh
#

set -e

echo "=== LetsBe Hub Setup ==="
echo ""

# Check if .env exists
if [[ ! -f .env ]]; then
    echo "ERROR: .env file not found!"
    echo "Copy .env.example to .env and fill in the values first."
    exit 1
fi

# Source .env to get variables
source .env

# Validate required variables
REQUIRED_VARS=(
    "HUB_URL"
    "HUB_DOMAIN"
    "POSTGRES_PASSWORD"
    "NEXTAUTH_SECRET"
    "CREDENTIAL_ENCRYPTION_KEY"
    "SETTINGS_ENCRYPTION_KEY"
)

for var in "${REQUIRED_VARS[@]}"; do
    if [[ -z "${!var}" || "${!var}" == *"CHANGE_ME"* ]]; then
        echo "ERROR: $var is not set or still has placeholder value"
        exit 1
    fi
done

echo "1. Creating job directories..."
JOBS_DIR="${JOBS_HOST_DIR:-/opt/letsbe-hub/jobs}"
LOGS_DIR="${LOGS_HOST_DIR:-/opt/letsbe-hub/logs}"
mkdir -p "$JOBS_DIR" "$LOGS_DIR"
chmod 755 "$JOBS_DIR" "$LOGS_DIR"
echo "   Created: $JOBS_DIR"
echo "   Created: $LOGS_DIR"
echo ""

echo "2. Logging into Gitea registry..."
echo "   (You will need your Gitea username and password/token)"
docker login code.letsbe.solutions
echo ""

echo "3. Pulling images..."
docker pull code.letsbe.solutions/letsbe/hub:${HUB_IMAGE_TAG:-master}
docker pull code.letsbe.solutions/letsbe/ansible-runner:${DOCKER_IMAGE_TAG:-master}
docker pull postgres:16-alpine
echo ""

echo "=== Setup Complete ==="
echo ""
echo "Now run: docker compose up -d"
echo ""
echo "Then configure Docker Hub and Gitea credentials in:"
echo "  ${HUB_URL}/admin/settings"
