#!/usr/bin/env bash

set -Eeuo pipefail

APP_DIR="${1:-/var/www/html/sistema}"
SCRIPT_DIR="$(
    cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
    pwd
)"

if [[ ! -f "${APP_DIR}/artisan" ]]; then
    echo "Laravel não encontrado em: ${APP_DIR}" >&2
    exit 1
fi

apt-get update
apt-get install -y supervisor

install -D -m 0644 \
    "${SCRIPT_DIR}/deploy/supervisor/conectae-worker.conf" \
    /etc/supervisor/conf.d/conectae-worker.conf

mkdir -p "${APP_DIR}/storage/logs"
touch "${APP_DIR}/storage/logs/queue-worker.log"

chown -R www-data:www-data \
    "${APP_DIR}/storage" \
    "${APP_DIR}/bootstrap/cache"

systemctl enable --now supervisor

supervisorctl reread
supervisorctl update
supervisorctl restart conectae-worker:*

echo
supervisorctl status conectae-worker:*

echo
echo "Worker permanente instalado com sucesso."
