#!/usr/bin/bash
set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_DIR="${APP_DIR:-$(cd "$SCRIPT_DIR/.." && pwd)}"
BRANCH="${BRANCH:-staging}"
LOG="${LOG:-${APP_DIR}/deploy.log}"
GIT="${GIT:-/usr/local/cpanel/3rdparty/lib/path-bin/git}"
REPO_OWNER="${REPO_OWNER:-yousystemsnet}"
WEBHOOK_URL="${WEBHOOK_URL:-}"
NEXTJS_BUILD_CMD="${NEXTJS_BUILD_CMD:-npm run build}"
NEXTJS_INSTALL_CMD="${NEXTJS_INSTALL_CMD:-}"
NEXTJS_RESTART_CMD="${NEXTJS_RESTART_CMD:-pm2 restart coporatebackend-nextjs}"

log_msg() {
  echo "$(date -Iseconds) $*" >> "$LOG"
}

fail() {
  log_msg "ERROR: $*"
  send_webhook "failed" "Deploy failed (Next.js)" "$*"
  log_msg "==== DEPLOY FAILED (Next.js) ===="
  exit 1
}

send_webhook() {
  local message="$2"
  local details="$3"

  if [ -z "$WEBHOOK_URL" ]; then
    return 0
  fi

  local full_text="${message}"
  if [ -n "$details" ]; then
    full_text="${full_text}"$'\n'"${details}"
  fi

  full_text="${full_text//\\/\\\\}"
  full_text="${full_text//\"/\\\"}"
  full_text="${full_text//$'\n'/\\n}"
  local payload="{\"text\":\"${full_text}\"}"

  curl -s -X POST "$WEBHOOK_URL" \
    -H "Content-Type: application/json" \
    -d "$payload" \
    --max-time 10 \
    --connect-timeout 5 > /dev/null 2>&1
}

export REPO_HOME="${REPO_HOME:-/home/${REPO_OWNER}}"
export HOME="$REPO_HOME"
export PATH="/usr/bin:/bin:/usr/local/bin:${PATH:-}"
export GIT_SSH_COMMAND="ssh -F ${REPO_HOME}/.ssh/config -o BatchMode=yes -o StrictHostKeyChecking=accept-new"
export NODE_ENV="${NODE_ENV:-production}"
export NEXT_TELEMETRY_DISABLED="${NEXT_TELEMETRY_DISABLED:-1}"

log_msg "==== DEPLOY (Next.js) START (user=$(whoami) app=$APP_DIR branch=$BRANCH) ===="

if [ ! -d "$APP_DIR" ]; then
  fail "APP_DIR does not exist: $APP_DIR"
fi

cd "$APP_DIR" || fail "Cannot cd to $APP_DIR"

if [ ! -x "$GIT" ] && ! command -v git >/dev/null 2>&1; then
  fail "git not found (GIT=$GIT)"
fi
if [ ! -x "$GIT" ]; then
  GIT="$(command -v git)"
fi

$GIT config --global --add safe.directory "$APP_DIR" 2>/dev/null || true

if [ ! -d "$APP_DIR/.git" ]; then
  fail "Not a git repo: $APP_DIR/.git missing"
fi

if ! test -w "$APP_DIR/.git"; then
  fail "Cannot write to $APP_DIR/.git (running as $(whoami))"
fi

export GIT_USERNAME="${GIT_USERNAME:-}"
export GIT_PASSWORD="${GIT_PASSWORD:-}"
if [ -f "$APP_DIR/.deploy_env" ] && [ -r "$APP_DIR/.deploy_env" ]; then
  set -a
  # shellcheck source=/dev/null
  source "$APP_DIR/.deploy_env"
  set +a
  export GIT_USERNAME="${GIT_USERNAME:-}"
  export GIT_PASSWORD="${GIT_PASSWORD:-}"
  WEBHOOK_URL="${WEBHOOK_URL:-}"
  log_msg "Loaded $APP_DIR/.deploy_env"
fi

git_pull_ssh() {
  log_msg "git pull origin $BRANCH (SSH/key)"
  if $GIT pull origin "$BRANCH" >> "$LOG" 2>&1; then
    return 0
  fi
  return 1
}

PULL_EXIT=1
if git_pull_ssh; then
  PULL_EXIT=0
fi

if [ "$PULL_EXIT" -ne 0 ]; then
  fail "git pull failed (see last lines in $LOG)"
fi

if [ ! -f "$APP_DIR/package.json" ]; then
  fail "APP_DIR has no package.json: $APP_DIR"
fi

log_msg "==== NEXTJS BUILD START ===="

if [ -z "$NEXTJS_INSTALL_CMD" ]; then
  (cd "$APP_DIR" && npm ci --prefer-offline) >> "$LOG" 2>&1 || \
    (cd "$APP_DIR" && npm install --prefer-offline) >> "$LOG" 2>&1 || fail "npm install failed"
else
  (cd "$APP_DIR" && bash -c "$NEXTJS_INSTALL_CMD") >> "$LOG" 2>&1 || fail "NEXTJS_INSTALL_CMD failed"
fi

(cd "$APP_DIR" && bash -c "$NEXTJS_BUILD_CMD") >> "$LOG" 2>&1 || fail "NEXTJS_BUILD_CMD failed"

if [ -n "$NEXTJS_RESTART_CMD" ]; then
  (cd "$APP_DIR" && bash -c "$NEXTJS_RESTART_CMD") >> "$LOG" 2>&1 || fail "NEXTJS_RESTART_CMD failed"
fi

COMMIT_AUTHOR=$($GIT log -1 --format='%an' 2>/dev/null || true)
COMMIT_MSG=$($GIT log -1 --format='%s' 2>/dev/null || true)
CONTENT="Deployed Successfully (Next.js)"$'\n'"Author: ${COMMIT_AUTHOR}"$'\n'"Commit Message: ${COMMIT_MSG}"
WRAPPED=$'```\n'"$CONTENT"$'\n''```'
send_webhook "success" "$WRAPPED" ""

log_msg "==== DEPLOY (Next.js) END ===="
