#!/bin/bash

# Load .env file if it exists
if [ -f .env ]
then
  export $(cat .env | sed 's/#.*//g' | xargs)
fi

cmd_create_database() {
    echo "Creating right_tree database..."
    docker-compose down --remove-orphans --volumes
    docker-compose -f docker-compose.yaml up postgres | sed '/PostgreSQL init process complete; ready for start up./q'
    docker-compose down
}

cmd_makemigrations() {
    echo "Creating database migrations..."
    docker-compose exec django-backend python manage.py makemigrations --no-input
}

cmd_migrate() {
    echo "Running database migrations..."
    docker-compose exec django-backend python manage.py migrate
}

cmd_createsuperuser() {
    echo "Loading shapefiles into the database..."
    docker-compose exec django-backend python manage.py createsuperuser --noinput
}

cmd_load_fixtures() {
    echo "Loading fixtures..."
    docker-compose exec django-backend bash -c "python manage.py loaddata right_tree/api/data/fixtures/*.json"
}

cmd_load_shapefiles() {
    echo "Loading shapefiles into the database..."
    docker-compose exec django-backend python manage.py loadshapefiles
}

cmd_create_plant_fixtures() {
    echo "Creates fixtures for plants using spreadsheet."
    docker-compose exec django-backend python manage.py createplantfixtures
}

cmd_reset_plants() {
    echo "Resetting plants..."
    docker-compose exec django-backend python manage.py resetplants
}

cmd_load_plant_fixtures() {
    echo "Loading plants..."
    docker-compose exec django-backend python manage.py loaddata right_tree/api/data/fixtures/plants.json
}

cmd_load_plants() {
    cmd_create_plant_fixtures
    cmd_reset_plants
    cmd_load_plant_fixtures    
}

cmd_load_sites_from_spreadsheet() {
    echo "Loading habitats and zones..."
    docker-compose exec django-backend python manage.py loadsitedata
}

cmd_populate_database() {
    echo "Populating the database..."
    docker-compose up -d django-backend postgres

    cmd_makemigrations
    cmd_migrate
    cmd_createsuperuser
    cmd_load_fixtures
    cmd_load_shapefiles
    cmd_load_plants

    docker-compose down
}

cmd_init_database() {
    cmd_create_database
    cmd_populate_database
}

cmd_reset_database() {
    cmd_init_database
}

cmd_build() {
    docker-compose build
}

cmd_start() {
    docker-compose up
}

cmd_build_production() {
    docker-compose -f docker-compose.production.yaml build
}

cmd_start_production() {
    docker-compose -f docker-compose.production.yaml up  --remove-orphans
}

# Run the command
cmd="$1"
"cmd_$cmd" "$@"
