name: Build And Deploy Main

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on:
      - ubuntu-latest
    env:
      PROJECT_DIR: /home/act_runner/temp/tspt
      GIT_REPO_URL: https://git.mayo.llc/yangli/worldshine-redesign.git
      GIT_USERNAME: ${{ secrets.USERNAME }}
      GIT_PASSWORD: ${{ secrets.PASSWORD }}
      REMOTE_HOST: 34.232.175.208
      REMOTE_USER: rocky
      SSH_KEY: /home/act_runner/ssh-certs/charlie_ws.pem
      REMOTE_APP_ROOT: /www/wwwroot/worldshine1
      REMOTE_VIEWS_DIR: /www/wwwroot/worldshine1/app/views
      EXCLUDE_PATTERN: (^|/)\.DS_Store$|(^|/)_MACOSX(/|$)
      BEFORE_SHA: ${{ github.event.before }}
      AFTER_SHA: ${{ github.sha }}
    steps:
      - name: Ensure project checkout exists
        run: |
          set -e
          mkdir -p "$PROJECT_DIR"
          cd "$PROJECT_DIR"

          if [ ! -d ".git" ]; then
            if [ -n "$(ls -A . 2>/dev/null)" ]; then
              echo "Project dir exists but is not a git repo and not empty: $PROJECT_DIR"
              exit 1
            fi

            if [ -z "$GIT_USERNAME" ] || [ -z "$GIT_PASSWORD" ]; then
              echo "Missing USERNAME/GITEA_PASSWORD secrets."
              exit 1
            fi

            export GIT_TERMINAL_PROMPT=0
            ASKPASS_FILE="$(mktemp)"
            printf '%s\n' '#!/usr/bin/env sh' 'case "$1" in' '  *Username*) echo "$GIT_USERNAME" ;;' '  *Password*) echo "$GIT_PASSWORD" ;;' '  *) echo "" ;;' 'esac' > "$ASKPASS_FILE"
            chmod 700 "$ASKPASS_FILE"
            GIT_ASKPASS="$ASKPASS_FILE" git clone "$GIT_REPO_URL" .
            rm -f "$ASKPASS_FILE"
          fi

      - name: Pull latest main
        run: |
          set -e
          cd "$PROJECT_DIR"
          if [ -z "$GIT_USERNAME" ] || [ -z "$GIT_PASSWORD" ]; then
            echo "Missing GITEA_USERNAME/GITEA_PASSWORD secrets."
            exit 1
          fi
          export GIT_TERMINAL_PROMPT=0
          ASKPASS_FILE="$(mktemp)"
          printf '%s\n' '#!/usr/bin/env sh' 'case "$1" in' '  *Username*) echo "$GIT_USERNAME" ;;' '  *Password*) echo "$GIT_PASSWORD" ;;' '  *) echo "" ;;' 'esac' > "$ASKPASS_FILE"
          chmod 700 "$ASKPASS_FILE"
          GIT_ASKPASS="$ASKPASS_FILE" git fetch origin main
          git checkout main
          GIT_ASKPASS="$ASKPASS_FILE" git pull origin main
          rm -f "$ASKPASS_FILE"

      - name: Build client
        run: |
          set -e
          export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
          [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
          cd "$PROJECT_DIR/client"
          npm install
          CI=false npm run build

      - name: Replace local app views from client dist
        run: |
          set -e
          cd "$PROJECT_DIR"
          mkdir -p app/views
          rm -rf app/views/*
          rsync -a --delete --exclude ".DS_Store" --exclude "_MACOSX" client/build/ app/views/

      - name: Deploy views to remote server
        run: |
          set -e
          cd "$PROJECT_DIR"
          SSH_CMD="ssh -i $SSH_KEY -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
          RSYNC_RSH="ssh -i $SSH_KEY -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
          $SSH_CMD "$REMOTE_USER@$REMOTE_HOST" "sudo mkdir -p \"$REMOTE_VIEWS_DIR\""
          rsync -az --delete --exclude ".DS_Store" --exclude "_MACOSX" --rsync-path="sudo rsync" -e "$RSYNC_RSH" app/views/ "$REMOTE_USER@$REMOTE_HOST:$REMOTE_VIEWS_DIR/"

      - name: Deploy changed backend files only
        run: |
          set -e
          cd "$PROJECT_DIR"
          SSH_CMD="ssh -i $SSH_KEY -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
          RSYNC_RSH="ssh -i $SSH_KEY -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
          CHANGE_PATHS=(app/controllers app/middlewares app/models app/routes app/scheduler app/services)
          CHANGED_LIST_FILE="$(mktemp)"
          DELETED_LIST_FILE="$(mktemp)"
          DIRS_LIST_FILE="$(mktemp)"

          is_excluded_path() {
            case "$1" in
              *.DS_Store|*/.DS_Store|_MACOSX|_MACOSX/*|*/_MACOSX|*/_MACOSX/*) return 0 ;;
              *) return 1 ;;
            esac
          }

          if [ -n "$BEFORE_SHA" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then
            while IFS= read -r file; do
              [ -z "$file" ] && continue
              is_excluded_path "$file" && continue
              printf '%s\n' "$file" >> "$CHANGED_LIST_FILE"
            done < <(git diff --name-only --diff-filter=ACMRT "$BEFORE_SHA" "$AFTER_SHA" -- "${CHANGE_PATHS[@]}" || true)

            while IFS= read -r file; do
              [ -z "$file" ] && continue
              is_excluded_path "$file" && continue
              printf '%s\n' "$file" >> "$DELETED_LIST_FILE"
            done < <(git diff --name-only --diff-filter=D "$BEFORE_SHA" "$AFTER_SHA" -- "${CHANGE_PATHS[@]}" || true)
          else
            while IFS= read -r file; do
              [ -z "$file" ] && continue
              is_excluded_path "$file" && continue
              [ -f "$file" ] || continue
              printf '%s\n' "$file" >> "$CHANGED_LIST_FILE"
            done < <(git show --name-only --pretty="" "$AFTER_SHA" -- "${CHANGE_PATHS[@]}" || true)
          fi

          if [ ! -s "$CHANGED_LIST_FILE" ]; then
            echo "No backend file changes detected in target folders."
          else
            while IFS= read -r file; do
              [ -z "$file" ] && continue
              printf '%s\n' "$(dirname "$file")"
            done < "$CHANGED_LIST_FILE" | awk '!seen[$0]++' > "$DIRS_LIST_FILE"

            while IFS= read -r dir; do
              [ -z "$dir" ] && continue
              $SSH_CMD "$REMOTE_USER@$REMOTE_HOST" "sudo mkdir -p \"$REMOTE_APP_ROOT/$dir\""
            done < "$DIRS_LIST_FILE"

            rsync -az --files-from="$CHANGED_LIST_FILE" --exclude ".DS_Store" --exclude "_MACOSX" --rsync-path="sudo rsync" -e "$RSYNC_RSH" ./ "$REMOTE_USER@$REMOTE_HOST:$REMOTE_APP_ROOT/"
            echo "Deployed backend changes from CHANGE_PATHS."
          fi

          if [ -s "$DELETED_LIST_FILE" ]; then
            while IFS= read -r file; do
              [ -z "$file" ] && continue
              remote_file="$REMOTE_APP_ROOT/$file"
              $SSH_CMD "$REMOTE_USER@$REMOTE_HOST" "sudo rm -f \"$remote_file\""
              echo "Deleted on remote: $file"
            done < "$DELETED_LIST_FILE"
          fi

          rm -f "$CHANGED_LIST_FILE" "$DELETED_LIST_FILE" "$DIRS_LIST_FILE"
