name: Deploy Website

on:
  push:
    branches:
      - main
      - master

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Build Docker Image
        run: |
          docker build -t my-website:latest .

      - name: Stop and Remove Existing Container
        run: |
          docker stop website-container || true
          docker rm website-container || true

      - name: Prepare Host Storage
        run: |
          # The bind mount creates /server_storage on the host if missing.
          # Run a throwaway container to fix ownership so UID 1001 (nextjs) can write.
          docker run --rm -v /server_storage:/data alpine sh -c \
            "chown -R 1001:1001 /data && chmod -R go-rwx /data"

      - name: Run New Container
        run: |
          docker run -d \
            --name website-container \
            --restart unless-stopped \
            -p 8080:3000 \
            -e ANALYTICS_SALT="${{ secrets.ANALYTICS_SALT }}" \
            -e ADMIN_DASH_URL="${{ secrets.ADMIN_DASH_URL }}" \
            -e ADMIN_DASH_KEY="${{ secrets.ADMIN_DASH_KEY }}" \
            -v /server_storage:/server_storage \
            my-website:latest
