#!/usr/bin/env bash

set -Eeuo pipefail

SOURCE_DIR="${SOURCE_DIR:-/root/call-center}"
DEPLOY_DIR="${DEPLOY_DIR:-/home/gitlab-runner/deploy/call-center}"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run this script as root so it can read the current deployment under /root." >&2
  exit 1
fi

if [[ ! -d "$SOURCE_DIR/.data_local" ]]; then
  echo "Missing source data directory: $SOURCE_DIR/.data_local" >&2
  exit 1
fi

if [[ ! -f "$SOURCE_DIR/.env.production" ]]; then
  echo "Missing source env file: $SOURCE_DIR/.env.production" >&2
  exit 1
fi

install -d -o gitlab-runner -g gitlab-runner "$DEPLOY_DIR"
rsync -a --delete "$SOURCE_DIR/.data_local/" "$DEPLOY_DIR/.data_local/"
install -m 600 -o gitlab-runner -g gitlab-runner "$SOURCE_DIR/.env.production" "$DEPLOY_DIR/.env.production"
chown -R gitlab-runner:gitlab-runner "$DEPLOY_DIR/.data_local"

echo "Bootstrap complete: copied .data_local and .env.production into $DEPLOY_DIR"
