#!/bin/bash
#
# Copyright (c) 2025.  Ohio Department of Education. - All Rights Reserved.
# Unauthorized copying of this file, in any medium, is strictly prohibited.
# Written by the State Software Development Team (http://ssdt.oecn.k12.oh.us/)
#
#

#
# read required env variables
BASEDIR="$PWD"
source $BASEDIR/.env/ipdp-shared.properties
source $BASEDIR/.env/ipdp-app.properties
# docker login
echo "Attempting to login to $artifactUrl"
docker login $artifactUrl -u $artifactUser -p $artifactPassword
# docker pull db image
echo "Attempting to pull $artifactUrl/ipdp-app:$appVersion"
docker pull $artifactUrl/ipdp-app:$appVersion
#
# Builder docker run command based on settings in env files
echo "Building docker run command"
dockerRunCommand="docker run --name $entityId-ipdp-app
  --restart=unlipdp-stopped
  --network $entityId-ipdp-net
  -e SPRING_DATASOURCE_URL=jdbc:postgresql://$entityId-ipdp-db:5432/ipdpdb
  -e SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver
  -e SPRING_DATASOURCE_USERNAME=postgres
  -e SPRING_DATASOURCE_PASSWORD=$dbPassword
  -e SPRING_PROFILES_ACTIVE=prod
  -e APPLICATION_ADMIN_PASSWORD=$adminPassword
  -e APPLICATION_ADMIN_RESET=$resetAdminPassword
  -e USPS_CONFIGURATION_HOST=$uspsHost
  -e USPS_CONFIGURATION_PORT=$uspsPort
  -e USPS_CONFIGURATION_APIKEY=$uspsApiKey
  -e USPS_CONFIGURATION_REMOTEAPIKEY=$uspsRemoteApiKey
  -e USPS_CONFIGURATION_CONTEXT=$uspsContext
  -e JAVA_OPTS=$java_opts"
#
if [ ! -z "$virtualHost" ]; then
    dockerRunCommand="$dockerRunCommand -e VIRTUAL_HOST=$virtualHost"
fi
#
if [ ! -z "$virtualPort" ]; then
    dockerRunCommand="$dockerRunCommand -e VIRTUAL_PORT=$virtualPort"
fi
#
if [ ! -z "$letsencryptHost" ]; then
    dockerRunCommand="$dockerRunCommand -e LETSENCRYPT_HOST=$letsencryptHost"
fi
#
if [ ! -z "$letsencryptEmail" ]; then
    dockerRunCommand="$dockerRunCommand -e LETSENCRYPT_EMAIL=$letsencryptEmail"
fi
#
if [ ! -z "$hostPort" ]; then
    dockerRunCommand="$dockerRunCommand -p $hostPort"
fi
#
dockerRunCommand="$dockerRunCommand -d $artifactUrl/ipdp-app:$appVersion"
#
# Execute constructed docker run command to create $entityId-ipdp-app container connected to db and docker network
echo "Executing docker run command"
$dockerRunCommand
