#!/bin/bash

set -xe

APP_FOLDER=letter
CONTAINER_NAME=letter-werefox-cafe

MODE=$1
x=$(APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose ps | grep $CONTAINER_NAME | wc -l)

if [ "$MODE" == "" ] || [ "$MODE" != "build" && "$MODE" != "dev" && "$MODE" != "start" ]; then
    echo "Please use 'dev', 'build', or 'start' as an argument."
    exit 1
fi

if [ $x -eq 1 ]; then
    APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose rm -sf
fi

if [ ! -d "$(pwd)/src/$APP_FOLDER" ]; then
    APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose run $CONTAINER_NAME sh -c "npm install --silent create-next-app && \
        npx create-next-app /usr/src/app/$APP_FOLDER --ts --eslint && \
        cd $APP_FOLDER && npm install tailwindcss autoprefixer &&  npx tailwindcss init -p && \
        cd /usr/src/app && rm -rf node_modules package.json package-lock.json"
fi


APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose run $CONTAINER_NAME sh -c "cd $APP_FOLDER && npm install --silent"
APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose run $CONTAINER_NAME sh -c "cd $APP_FOLDER && npx next telemetry disable"

if [ "$MODE" == "build" ]; then
    APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose run $CONTAINER_NAME sh -c "cd $APP_FOLDER && npm run build"
elif [ "$MODE" == "dev" ] || [ "$MODE" == "start" ]; then
    APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose up -d
    APP_FOLDER=$APP_FOLDER MODE=$MODE docker compose logs -f
fi
