#!/bin/bash

if [[ -z $1 ]]; then
  start_port=5000
else
  start_port=$1
fi

rebase=false
develop=false

for arg in "$@"
do
    if [ "$arg" == "-rebase" ]; then
      rebase=true
    fi
    if [ "$arg" == "-dev" ]; then
      develop=true
    fi
done

if [ "$1" == "-rebase" ]; then
    rebase=true
else
    rebase=false
fi

if [ ! -d "logs" ]; then
    mkdir -p "logs"
fi

if [ "$rebase" == true ]; then
    touch ./.create
    touch ./.init
    echo "The setup is complete. Start in normal mode."
    exit 1
else
    if [ ! -d "migrations" ]; then
        if [ "$develop" != true ]; then
          python3 -m venv venv
          source ./venv/bin/activate
        fi

        pip install --no-cache-dir -r requirements.txt

        sed -i 's/DISABLING_TASK=.*/DISABLING_TASK=True/g' .env

        flask db init
        flask db migrate
        flask db upgrade

        touch ./.create

        sed -i 's/DISABLING_TASK=.*/DISABLING_TASK=False/g' .env

        if [ "$develop" != true ]; then
          deactivate
        fi
    fi
fi

if [ "$develop" != true ]; then
  source ./venv/bin/activate
  nohup flask run --host=0.0.0.0 --port="$start_port" > logs/flask.log 2>&1 &
  sed -i "s/processes=\$(lsof -ti :.*)/processes=\$(lsof -ti :$start_port)/g" stop.sh

  echo $! > flask.pid
else
  python app.py > logs/flask.log 2>&1 &
  echo $! > flask.pid
fi
