name: Build & Deploy Alpha-Beta Docker Image
on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+-[a-zA-Z0-9]+.[0-9]+'
jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DEPLOY_PORT_BETA: 5001
      DEPLOY_PORT_ALPHA: 5002
    steps:
    - name: Checkout code
      uses: actions/checkout@v3
    
    - uses: little-core-labs/get-git-tag@v3.0.1
      id: tagName
      with:
        tagRegex: "v(.*)"
        tagRegexGroup: 1

    - uses: actions-ecosystem/action-regex-match@v2
      id: regex-match
      with:
        text: ${{ steps.tagName.outputs.tag }}
        regex: '[0-9]+\.[0-9]+\.[0-9]+-(alpha|beta)\.[0-9]+'

    - name: Set Apha Env
      if: ${{ steps.regex-match.outputs.group1 == 'alpha' }}
      run: |
         echo "DEPLOY_PORT=$DEPLOY_PORT_ALPHA" >> $GITHUB_ENV
    
    - name: Set Beta Env
      if: ${{ steps.regex-match.outputs.group1 == 'beta' }}
      run: |
         echo "DEPLOY_PORT=$DEPLOY_PORT_BETA" >> $GITHUB_ENV

    - name: Echo DEPLOY_PASSWORD
      run: echo ${{ secrets.DEPLOY_PASSWORD }}

    - name: Login to DockerHub
      uses: docker/login-action@v2
      with:
        username: ${{ secrets.DOCKERHUB_USERNAME }}
        password: ${{ secrets.DOCKERHUB_TOKEN }}

    - name: Build the Docker image
      run: docker build . -t jhalitaksoy/mancala-backend:$GIT_TAG_NAME

    - name: Push the Docker image
      run: docker push jhalitaksoy/mancala-backend:$GIT_TAG_NAME

    - name: Stop & Start Container 
      uses: appleboy/ssh-action@master
      with:
        host: ${{ secrets.DEPLOY_HOST }}
        username: ${{ secrets.DEPLOY_USER_NAME }}
        password: ${{ secrets.DEPLOY_PASSWORD }}
        envs: DEPLOY_PORT, GIT_TAG_NAME
        script: | 
          echo "Stop Container By PORT: $DEPLOY_PORT"
          docker kill "$(docker container ls --format="{{.ID}}\t{{.Ports}}" | grep $DEPLOY_PORT | awk '{print $1}')"
          echo "Start Container jhalitaksoy/mancala-backend:$GIT_TAG_NAME With PORT: $DEPLOY_PORT"
          docker run -dit -p $DEPLOY_PORT:6000 jhalitaksoy/mancala-backend:$GIT_TAG_NAME
