#!/usr/bin/env bash

set -Eeuo pipefail

log() {
    printf '[cpanel-deploy] %s\n' "$*"
}

die() {
    printf '[cpanel-deploy] ERROR: %s\n' "$*" >&2
    exit 1
}

command_path() {
    local candidate

    candidate="$(command -v "$1" 2>/dev/null || true)"
    if [[ -n "$candidate" ]]; then
        printf '%s\n' "$candidate"
    fi
}

escape_sed_replacement() {
    printf '%s' "$1" | sed -e 's/[\/&]/\\&/g'
}

sync_directory() {
    local source="$1"
    local target="$2"
    shift 2

    if command -v rsync >/dev/null 2>&1; then
        rsync -a --delete "$@" "$source"/ "$target"/
        return
    fi

    log "rsync nao encontrado; usando sincronizacao sem delete."
    mkdir -p "$target"
    tar -C "$source" -cf - "$@" . | tar -C "$target" -xf -
}

detect_webroot() {
    if [[ -n "${CPANEL_WEBROOT:-}" ]]; then
        printf '%s\n' "$CPANEL_WEBROOT"
        return
    fi

    if [[ -d "$HOME/fut.4cyber.com.br" ]]; then
        printf '%s\n' "$HOME/fut.4cyber.com.br"
        return
    fi

    if [[ -d "$HOME/public_html/fut" ]]; then
        printf '%s\n' "$HOME/public_html/fut"
        return
    fi

    if [[ -d "$HOME/public_html/fut.4cyber.com.br" ]]; then
        printf '%s\n' "$HOME/public_html/fut.4cyber.com.br"
        return
    fi

    die "Nao foi possivel detectar o WEBROOT. Defina CPANEL_WEBROOT em deploy/cpanel/.deploy.env."
}

REPO_DIR="${DEPLOY_REPO_DIR:-$(pwd)}"
DEPLOY_ENV_FILE="$REPO_DIR/deploy/cpanel/.deploy.env"

if [[ -f "$DEPLOY_ENV_FILE" ]]; then
    log "Carregando configuracao de $DEPLOY_ENV_FILE"
    # shellcheck disable=SC1090
    source "$DEPLOY_ENV_FILE"
fi

APP_NAME="${CPANEL_APP_NAME:-tropa-do-finin}"
APP_ROOT="${CPANEL_APP_ROOT:-$HOME/apps/$APP_NAME}"
APP_CURRENT="${CPANEL_APP_CURRENT:-$APP_ROOT/current}"
WEBROOT="$(detect_webroot)"
PHP_BIN="${CPANEL_PHP_BIN:-$(command_path php)}"
COMPOSER_BIN="${CPANEL_COMPOSER_BIN:-$(command_path composer)}"
INDEX_TEMPLATE="$REPO_DIR/deploy/cpanel/index.php.stub"
INDEX_TARGET="$WEBROOT/index.php"

[[ -d "$REPO_DIR" ]] || die "Repositorio nao encontrado em $REPO_DIR"
[[ -n "$PHP_BIN" ]] || die "PHP nao encontrado. Defina CPANEL_PHP_BIN em deploy/cpanel/.deploy.env."
[[ -n "$COMPOSER_BIN" ]] || die "Composer nao encontrado. Defina CPANEL_COMPOSER_BIN em deploy/cpanel/.deploy.env."
[[ -f "$INDEX_TEMPLATE" ]] || die "Template do index nao encontrado em $INDEX_TEMPLATE"

log "Repositorio: $REPO_DIR"
log "Aplicacao: $APP_CURRENT"
log "Webroot: $WEBROOT"

mkdir -p \
    "$APP_CURRENT" \
    "$APP_CURRENT/bootstrap/cache" \
    "$APP_CURRENT/storage/app/public" \
    "$APP_CURRENT/storage/framework/cache" \
    "$APP_CURRENT/storage/framework/sessions" \
    "$APP_CURRENT/storage/framework/views" \
    "$APP_CURRENT/storage/logs" \
    "$WEBROOT"

log "Sincronizando codigo para a pasta da aplicacao"
sync_directory "$REPO_DIR" "$APP_CURRENT" \
    --exclude .git \
    --exclude .env \
    --exclude vendor \
    --exclude storage \
    --exclude bootstrap/cache \
    --exclude deploy/cpanel/.deploy.env

if [[ ! -f "$APP_CURRENT/.env" ]]; then
    die "Arquivo .env ausente em $APP_CURRENT/.env. Crie-o no servidor e rode o deploy novamente."
fi

log "Instalando dependencias PHP"
(
    cd "$APP_CURRENT"
    "$COMPOSER_BIN" install --no-dev --optimize-autoloader --no-interaction --prefer-dist
)

log "Ajustando permissoes de escrita"
chmod -R u+rwX,go-rwx "$APP_CURRENT/storage" "$APP_CURRENT/bootstrap/cache"

log "Limpando caches antigas do Laravel"
(
    cd "$APP_CURRENT"
    "$PHP_BIN" artisan optimize:clear
)

log "Executando migracoes"
(
    cd "$APP_CURRENT"
    "$PHP_BIN" artisan migrate --force
)

log "Gerando caches de producao"
(
    cd "$APP_CURRENT"
    "$PHP_BIN" artisan config:cache
    "$PHP_BIN" artisan route:cache
    "$PHP_BIN" artisan view:cache
)

log "Publicando arquivos publicos"
sync_directory "$APP_CURRENT/public" "$WEBROOT" \
    --exclude storage \
    --exclude .well-known \
    --exclude cgi-bin

log "Gerando index.php publico"
sed "s/{{APP_CURRENT}}/$(escape_sed_replacement "$APP_CURRENT")/g" \
    "$INDEX_TEMPLATE" > "$INDEX_TARGET"

if [[ -L "$WEBROOT/storage" ]]; then
    rm -f "$WEBROOT/storage"
elif [[ -e "$WEBROOT/storage" ]]; then
    die "$WEBROOT/storage ja existe e nao e um link simbolico. Mova esse conteudo para $APP_CURRENT/storage/app/public antes de rodar novamente."
fi

log "Criando link simbolico para storage publica"
ln -s "$APP_CURRENT/storage/app/public" "$WEBROOT/storage"

log "Deploy concluido com sucesso"
