#!/usr/bin/env bash set -Eeuo pipefail DEFAULT_REPOSITORY="https://git.mydeploy.cloud/Erik/setapi.git" REPOSITORY="${SETAPI_REPOSITORY:-$DEFAULT_REPOSITORY}" REF="${SETAPI_REF:-codex/setapi-vps-bootstrap-versioning}" INSTALL_DIR="${SETAPI_INSTALL_DIR:-/opt/setapi-platform}" PUBLIC_PORT="${SETAPI_BOOTSTRAP_PORT:-8080}" ENV_FILE="" exec 3>&1 say() { printf '\n[SETAPI] %s\n' "$*" >&3; } fail() { printf '\n[SETAPI] ERRO: %s\n' "$*" >&3; exit 1; } # Splits https://servidor[:porta]/dono/nome[.git] into the three settings the check for updates needs ("URL dono nome"). derive_update_source() { local url="$1" [[ "$url" =~ ^https://([A-Za-z0-9.-]+(:[0-9]{1,5})?)/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)$ ]] || return 1 local owner="${BASH_REMATCH[3]}" name="${BASH_REMATCH[4]}" name="${name%.git}" [[ -n "$name" && "$owner" != . && "$owner" != .. && "$name" != . && "$name" != .. ]] || return 1 printf 'https://%s %s %s\n' "${BASH_REMATCH[1]}" "$owner" "$name" } [[ "$EUID" -eq 0 ]] || fail "Execute como root: sudo bash install.sh" [[ "$PUBLIC_PORT" =~ ^[0-9]{1,5}$ ]] && (( PUBLIC_PORT >= 1 && PUBLIC_PORT <= 65535 )) || fail "Porta inválida: $PUBLIC_PORT" [[ "$INSTALL_DIR" == /* && "$INSTALL_DIR" != "/" ]] || fail "SETAPI_INSTALL_DIR deve ser um caminho absoluto específico." [[ "$REF" =~ ^[A-Za-z0-9._/-]+$ && "$REF" != *..* ]] || fail "Branch/tag de instalação inválida." # The code and the updates can come from another server (a mirror, a company's own Gitea). The check for updates talks to a # Gitea/Forgejo API, so a source other than the default must be https://servidor/dono/nome(.git) on one of those. SOURCE_PARTS="" if [[ "$REPOSITORY" != "$DEFAULT_REPOSITORY" ]]; then SOURCE_PARTS="$(derive_update_source "$REPOSITORY")" || fail "SETAPI_REPOSITORY deve ser https://servidor/dono/nome(.git) de um servidor Gitea ou Forgejo." fi command -v apt-get >/dev/null || fail "Este instalador inicial suporta Debian/Ubuntu (apt-get)." INSTALL_LOG="$(umask 077; mktemp /var/log/setapi-install-XXXXXXXX.log)" chmod 600 "$INSTALL_LOG" # Technical command output stays in a private diagnostic file. User-facing # messages and the one-time access code go only to the original terminal. exec >>"$INSTALL_LOG" 2>&1 # Bootstrap packages run unattended so needrestart/debconf cannot wait for a # confirmation in the terminal while installer output is redirected to a log. export DEBIAN_FRONTEND=noninteractive export NEEDRESTART_MODE=a STEP_NUMBER=0 STEP_TITLE="" STEP_STARTED=$SECONDS ACTIVE_COMMAND="" STEP_PROGRESS_PID="" stop_step_progress() { if [[ -n "$STEP_PROGRESS_PID" ]]; then kill "$STEP_PROGRESS_PID" 2>/dev/null || true wait "$STEP_PROGRESS_PID" 2>/dev/null || true STEP_PROGRESS_PID="" fi } complete_step() { stop_step_progress say "Concluído: $STEP_TITLE ($((SECONDS - STEP_STARTED))s)." } start_step_progress() { local title="$STEP_TITLE" started="$STEP_STARTED" ( timer_pid="" next_notice=10 elapsed=0 trap 'if [[ -n "$timer_pid" ]]; then kill "$timer_pid" 2>/dev/null || true; wait "$timer_pid" 2>/dev/null || true; fi; exit 0' INT TERM while :; do sleep 2 & timer_pid=$! wait "$timer_pid" || true timer_pid="" elapsed=$((SECONDS - started)) if (( elapsed >= next_notice )); then say "$title — em andamento há ${elapsed}s." next_notice=$((next_notice + 10)) fi done ) & STEP_PROGRESS_PID=$! } step() { if (( STEP_NUMBER > 0 )); then complete_step fi STEP_NUMBER=$((STEP_NUMBER + 1)) STEP_TITLE="$1" STEP_STARTED=$SECONDS say "[$STEP_NUMBER/3] $STEP_TITLE" start_step_progress } phase() { if (( STEP_NUMBER > 0 )); then complete_step fi STEP_TITLE="$1" STEP_STARTED=$SECONDS say "$STEP_TITLE" start_step_progress } finish() { local result=$? trap - EXIT INT TERM if [[ -n "$ACTIVE_COMMAND" ]]; then kill "$ACTIVE_COMMAND" 2>/dev/null || true wait "$ACTIVE_COMMAND" 2>/dev/null || true fi stop_step_progress if (( result != 0 )); then say "Não foi possível concluir: ${STEP_TITLE:-início da instalação}." say "Detalhes técnicos para diagnóstico: $INSTALL_LOG (acesso somente do administrador)." fi exit "$result" } trap finish EXIT trap 'exit 130' INT trap 'exit 143' TERM run_with_progress() { "$@" & ACTIVE_COMMAND=$! local result=0 while kill -0 "$ACTIVE_COMMAND" 2>/dev/null; do sleep 2 done wait "$ACTIVE_COMMAND" || result=$? ACTIVE_COMMAND="" return "$result" } say "Instalação do SETAPI. Acompanhe as etapas abaixo; algumas podem levar alguns minutos." say "Detalhes técnicos: $INSTALL_LOG (arquivo privado)." step "Verificando o Docker" if ! command -v docker >/dev/null; then say "Docker não encontrado. Começando a instalação." printf 'Instalando Docker para %s\n' "$(. /etc/os-release && printf '%s' "$ID")" . /etc/os-release case "$ID" in ubuntu) DOCKER_OS=ubuntu ;; debian) DOCKER_OS=debian ;; *) fail "Distribuição não suportada automaticamente: $ID. Instale Docker Engine e Compose plugin e execute novamente." ;; esac ARCH="$(dpkg --print-architecture)" CODENAME="${VERSION_CODENAME:-}" [[ -n "$CODENAME" ]] || fail "Não foi possível identificar a versão da distribuição." apt-get update apt-get install -y ca-certificates curl install -m 0755 -d /etc/apt/keyrings curl -fsSL "https://download.docker.com/linux/$DOCKER_OS/gpg" -o /etc/apt/keyrings/docker.asc chmod a+r /etc/apt/keyrings/docker.asc printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/%s %s stable\n' "$ARCH" "$DOCKER_OS" "$CODENAME" > /etc/apt/sources.list.d/docker.list apt-get update apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin systemctl enable --now docker else say "Docker encontrado. Conferindo o serviço." fi docker info >/dev/null 2>&1 || fail "Docker está instalado, mas o daemon não respondeu. Verifique: systemctl status docker" if ! docker compose version >/dev/null 2>&1; then say "Docker Compose não encontrado. Começando a instalação." apt-get update && apt-get install -y docker-compose-plugin fi say "Docker verificado e pronto." step "Instalando os containers do SETAPI" if ! command -v git >/dev/null || ! command -v openssl >/dev/null; then apt-get update command -v git >/dev/null || apt-get install -y git command -v openssl >/dev/null || apt-get install -y openssl fi if [[ -e "$INSTALL_DIR" ]]; then [[ -d "$INSTALL_DIR/.git" ]] || fail "$INSTALL_DIR já existe e não parece ser um clone Git. O instalador não vai sobrescrever essa pasta." git -C "$INSTALL_DIR" remote get-url origin >/dev/null 2>&1 || fail "O clone existente não tem remote origin; inspecione-o antes de continuar." [[ "$(git -C "$INSTALL_DIR" remote get-url origin)" == "$REPOSITORY" ]] || fail "Já existe outro repositório em $INSTALL_DIR. Preserve-o e escolha outra SETAPI_INSTALL_DIR." [[ -z "$(git -C "$INSTALL_DIR" status --porcelain)" ]] || fail "O clone em $INSTALL_DIR contém alterações locais. O instalador não vai descartá-las." say "Repositório existente confirmado; sem pull ou sobrescrita automática." else git clone --depth 1 --branch "$REF" "$REPOSITORY" "$INSTALL_DIR" fi cd "$INSTALL_DIR" [[ -f docker-compose.yml && -f apps/api/Dockerfile && -f apps/web/Dockerfile ]] || fail "O repositório não contém todos os arquivos do instalador." ENV_FILE="$INSTALL_DIR/.env.bootstrap" if [[ ! -e "$ENV_FILE" ]]; then umask 077 POSTGRES_SECRET="$(openssl rand -hex 32)" BOOTSTRAP_SECRET="$(openssl rand -hex 24)" ( set -o noclobber; printf 'SETAPI_POSTGRES_PASSWORD=%s\nSETAPI_BOOTSTRAP_TOKEN=%s\nSETAPI_BOOTSTRAP_PORT=%s\n' "$POSTGRES_SECRET" "$BOOTSTRAP_SECRET" "$PUBLIC_PORT" > "$ENV_FILE" ) || fail "Não foi possível criar o arquivo de ambiente com segurança." chmod 600 "$ENV_FILE" NEW_INSTALL=1 else chmod 600 "$ENV_FILE" NEW_INSTALL=0 say "Segredos existentes preservados em $ENV_FILE." fi SAVED_PUBLIC_PORT="$(sed -n 's/^SETAPI_BOOTSTRAP_PORT=//p' "$ENV_FILE" | tail -n 1)" PUBLIC_PORT="${SETAPI_BOOTSTRAP_PORT:-${SAVED_PUBLIC_PORT:-8080}}" [[ "$PUBLIC_PORT" =~ ^[0-9]{1,5}$ ]] && (( PUBLIC_PORT >= 1 && PUBLIC_PORT <= 65535 )) || fail "Porta de acesso salva inválida." BUILD_VERSION="$(git rev-parse HEAD)" if grep -q '^SETAPI_BUILD_VERSION=' "$ENV_FILE"; then sed -i "s/^SETAPI_BUILD_VERSION=.*/SETAPI_BUILD_VERSION=$BUILD_VERSION/" "$ENV_FILE" else printf '\nSETAPI_BUILD_VERSION=%s\n' "$BUILD_VERSION" >> "$ENV_FILE" fi if grep -q '^SETAPI_UPDATE_BRANCH=' "$ENV_FILE"; then sed -i "s|^SETAPI_UPDATE_BRANCH=.*|SETAPI_UPDATE_BRANCH=$REF|" "$ENV_FILE" else printf 'SETAPI_UPDATE_BRANCH=%s\n' "$REF" >> "$ENV_FILE" fi # Updates and the check for updates must read the same source, so a custom one is saved for both. set_env() { if grep -q "^$1=" "$ENV_FILE"; then sed -i "s|^$1=.*|$1=$2|" "$ENV_FILE"; else printf '%s=%s\n' "$1" "$2" >> "$ENV_FILE"; fi } if [[ -n "$SOURCE_PARTS" ]]; then read -r SOURCE_URL SOURCE_OWNER SOURCE_NAME <<<"$SOURCE_PARTS" set_env SETAPI_UPDATE_GITEA_URL "$SOURCE_URL" set_env SETAPI_UPDATE_REPOSITORY_OWNER "$SOURCE_OWNER" set_env SETAPI_UPDATE_REPOSITORY_NAME "$SOURCE_NAME" fi # A new installation does not use an outside catalog: the products that come with the Central need none. An operator can still # point SETAPI_CATALOG_URL at one. Installations that already exist keep what they have. if [[ "$NEW_INSTALL" -eq 1 ]] && ! grep -q '^SETAPI_CATALOG_URL=' "$ENV_FILE"; then printf 'SETAPI_CATALOG_URL=%s\n' "${SETAPI_CATALOG_URL:-}" >> "$ENV_FILE" fi chmod 600 "$ENV_FILE" if ! grep -q '^SETAPI_RESOURCE_ENCRYPTION_KEY=' "$ENV_FILE"; then RESOURCE_ENCRYPTION_KEY="$(openssl rand -hex 32)" printf 'SETAPI_RESOURCE_ENCRYPTION_KEY=%s\n' "$RESOURCE_ENCRYPTION_KEY" >> "$ENV_FILE" unset RESOURCE_ENCRYPTION_KEY fi chmod 600 "$ENV_FILE" SETAPI_UPDATE_BRANCH="$REF" bash scripts/install-update-agent.sh SETAPI_INSTALL_DIR="$INSTALL_DIR" bash scripts/install-resource-agent.sh PUBLIC_IP="$(curl -4fsS --max-time 5 https://api.ipify.org 2>/dev/null || true)" if [[ "$PUBLIC_IP" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then if grep -q '^SETAPI_PUBLIC_IP=' "$ENV_FILE"; then sed -i "s/^SETAPI_PUBLIC_IP=.*/SETAPI_PUBLIC_IP=$PUBLIC_IP/" "$ENV_FILE" else printf 'SETAPI_PUBLIC_IP=%s\n' "$PUBLIC_IP" >> "$ENV_FILE" fi fi chmod 600 "$ENV_FILE" COMPOSE_ARGS=(--env-file "$ENV_FILE" -p setapi -f docker-compose.yml) DOMAIN_OVERRIDE=/var/lib/setapi-resource-agent/domain-compose.yml if [[ -f "$DOMAIN_OVERRIDE" ]]; then COMPOSE_ARGS+=(-f "$DOMAIN_OVERRIDE"); fi docker compose "${COMPOSE_ARGS[@]}" config -q run_with_progress docker compose "${COMPOSE_ARGS[@]}" build run_with_progress docker compose "${COMPOSE_ARGS[@]}" up -d --wait step "Preparando banco de dados e Storage padrão dos projetos" if ! run_with_progress systemctl start setapi-resource-agent.service; then fail "Não foi possível iniciar a preparação dos serviços padrão dos projetos." fi CATALOG_STATUS_FILE=/var/lib/setapi-resource-status/catalog-services.json if [[ ! -s "$CATALOG_STATUS_FILE" ]] || ! grep -q '"state":"ready"' "$CATALOG_STATUS_FILE"; then fail "O banco de dados e o Storage padrão dos projetos não foram confirmados. Consulte o diagnóstico técnico." fi say "Banco de dados e Storage padrão preparados." phase "Finalizando e verificando o acesso ao painel" PANEL_READY=0 for attempt in {1..15}; do if curl -fsS --max-time 5 "http://127.0.0.1:$PUBLIC_PORT/api/bootstrap/status" >/dev/null; then PANEL_READY=1 break fi [[ "$attempt" -eq 15 ]] || sleep 2 done [[ "$PANEL_READY" -eq 1 ]] || fail "O painel ainda não respondeu. Os serviços foram preservados; consulte os detalhes técnicos." complete_step if [[ -z "$PUBLIC_IP" ]]; then PUBLIC_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"; fi [[ -n "$PUBLIC_IP" ]] || PUBLIC_IP="IP_DA_VPS" say "Tudo pronto! Acesse: http://$PUBLIC_IP:$PUBLIC_PORT" if [[ "$NEW_INSTALL" -eq 1 ]]; then printf '\nChave de instalação para o primeiro acesso:\n%s\n' "$BOOTSTRAP_SECRET" >&3 else printf '\nA chave de instalação existente foi preservada e não foi exibida novamente.\n' >&3 fi