#!/bin/bash

VERSION="2025.05.12-1430"

usage() {
	  cat << EOF
DotDockerBuilder8 Version:$VERSION
  Arguments:
    -D|--directory      (optional)  path to solution folder
    -S|--solution       (mandatory) solution name
    -P|--project        (mandatory) project name
    -p|--port           (mandatory) exposed port
    -G|--git            (optional)  git URI                     (gitea.a.ucnit.eu)
    -U|--gituser        (optional)  authorized git user         (docker | gitea organization)
    -A|--accesstoken    (optional)  accesstoken for git user
    -h|--help           this text
EOF
  exit
}

[ $# -eq 0 ] && usage

DIRECTORY=""
SOLUTION=""
PROJECT=""
EXPOSED_PORT="8080"				# Since 2024, port 8080 is the standard web port for .NET

while [[ $# -gt 0 ]]; do
  case $1 in
    -D|--directory)
      DIRECTORY="$2"
      shift # past argument
      shift # past value
      ;;
    -S|--solution)
      SOLUTION="$2"
      shift # past argument
      shift # past value
      ;;
    -P|--project)
      PROJECT="$2"
      shift # past argument
      shift # past value
      ;;
    -p|--port)
      EXPOSED_PORT="$2"
      shift # past argument
      shift # past value
      ;;
    -G|--git)
      Git="$2"
      shift # past argument
      shift # past value
      ;;
    -U|--gituser)
      GitUser="$2"
      shift # past argument
      shift # past value
      ;;
    -A|--accesstoken)
      AccessToken="$2"
      shift # past argument
      shift # past value
      ;;
    -h|--help)
	  usage
	  ;;
    -*|--*)
      echo "Unknown option $1"
      usage
      ;;
    *)
      shift # past argument
      ;;
  esac
done

[ -n "$DIRECTORY" ] && cd $DIRECTORY



if [ ! -e $SOLUTION/$PROJECT/$PROJECT.csproj ]; then
  echo "Error, Not found: $SOLUTION/$PROJECT/$PROJECT.csproj"
  echo "Executed from $(pwd)"
  cat << EOF
Usage:
  $0 (-S|--solution) solution (-P|--project) project (-p|--port) exposed_port
  Please call from just outside solution folder
EOF
  echo "Current directory: $(pwd)"
  exit
fi

RUNDIR=$pwd
thisArch=$(uname -m)
myRuntime="UNKNOWN"
[ "$thisArch" == "x86_64" ] && myRuntime="linux-x64"
[ "$thisArch" == "aarch64" ] && myRuntime="linux-arm64"

# Dockerfile.dotbuild is executed from parent of solution
cat << EOF > Dockerfile.dotbuild
# Version 2024.01.26 1702
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
WORKDIR /app
EXPOSE $EXPOSED_PORT

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY $SOLUTION ./
RUN pwd
RUN dotnet restore "$PROJECT/$PROJECT.csproj"
RUN dotnet build "$PROJECT/$PROJECT.csproj" -c Release --self-contained --runtime $myRuntime -o /app/build
RUN ls -lR /app

FROM build AS publish
RUN dotnet publish "$PROJECT/$PROJECT.csproj" -c Release --self-contained --runtime $myRuntime -o /app/publish
RUN ls -lR /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
#ENTRYPOINT ["dotnet", "$PROJECT.dll"]
### New section
### CHECK_PORTS="mysql:3306 rabbitMQ:5672"
COPY start.dotbuild ./kajestartup.sh
RUN chmod 755 kajestartup.sh
CMD ./kajestartup.sh
RUN pwd
RUN ls -l
RUN cat ./kajestartup.sh
EOF

cat << EOF > start.dotbuild
#!/bin/bash
echo "Version 22.10.15 1446"
if [ -n "\$CHECK_PORTS" ]; then
  echo "Must check ports before start"
  ! which nc >/dev/null && apt-get update && apt-get -y install netcat
  for nn in \$(echo "\$CHECK_PORTS" | tr ';' ' '); do
    xHost=\$(echo "\$nn" | cut -f 1 -d ':')
    xPort=\$(echo "\$nn" | cut -f 2 -d ':')
    echo "Checking Host: \$xHost  Port: \$xPort"
    while ! nc -z -v \$xHost \$xPort; do
      echo "Waiting for Host: \$xHost  Port: \$xPort"
      sleep 5
    done
    echo "Checking Host: \$xHost  Port: \$xPort ... OK"
  done
  echo "Checking ports done..."
fi
# Adding DOCKER_HOST will cause an entry in /etc/hosts for local access to host platform
if [ -n "\$DOCKER_HOST" ] && grep -qv "KAJE" /etc/hosts; then
  echo "Adding DOCKER_HOST to /etc/hosts"
  b0=\$(cat /proc/net/route | sed -n '2,2 p' | cut -b 21-22)
  b1=\$(cat /proc/net/route | sed -n '2,2 p' | cut -b 19-20)
  b2=\$(cat /proc/net/route | sed -n '2,2 p' | cut -b 17-18)
  b3=\$(cat /proc/net/route | sed -n '2,2 p' | cut -b 15-16)
  echo "\$((16#\$b0)).\$((16#\$b1)).\$((16#\$b2)).\$((16#\$b3))  \$DOCKER_HOST" >> /etc/hosts
  echo "# KAJE WAS HERE" >> /etc/hosts
  echo "Changed /etc/hosts:"
  cat /etc/hosts
fi
echo "Starting: \$(date)"
dotnet $PROJECT.dll
[ "\$ZOMBIE" == "YES" ] && echo "ZOMBIE STATE ENTERED" && sleep 1d
EOF

# We are just outside solution folder
tagName=$(echo "$PROJECT" | tr '[:upper:]' '[:lower:]')

pwd
if [ -e $SOLUTION/$PROJECT/$PROJECT.csproj ]; then
	echo "Project file OK"
else
	echo "Project file NOK"
	exit
fi
echo "--------------"
cat ./Dockerfile.dotbuild
echo "--------------"

echo "docker build --file ./Dockerfile.dotbuild --tag=$tagName:latest ."
sudo docker build --file ./Dockerfile.dotbuild --tag=$tagName:latest .

if [ -n "$Git" ]; then
	CONTAINERNAME=$(echo -n "$Git/$GitUser/$tagName" | tr '[:upper:]' '[:lower:]')
	sudo docker image rm $CONTAINERNAME:latest
	sudo docker image rm $CONTAINERNAME:$(date +%y%m%d)
	sudo docker image tag $tagName:latest $CONTAINERNAME:latest
	sudo docker image tag $tagName:latest $CONTAINERNAME:$(date +%y%m%d)
	sudo docker image ls
	echo "Pushing images to repository"
	sudo docker login $Git --username=$GitUser --password=$AccessToken
	echo "docker push $CONTAINERNAME:latest"
	sudo docker push $CONTAINERNAME:latest
	echo "docker push $CONTAINERNAME:$(date +%y%m%d)"
	sudo docker push $CONTAINERNAME:$(date +%y%m%d)

	echo "Cleaning up: [$tagName:latest] [$CONTAINERNAME:latest] [$CONTAINERNAME:$(date +%y%m%d)]"
	sudo docker image rm $tagName:latest
	sudo docker image rm $CONTAINERNAME:latest $CONTAINERNAME:$(date +%y%m%d)
else
	echo "Not pushing to package repository as Git[$Git] or GitUser[$GitUser] is blank"
fi

sudo docker image prune --force
echo "Done..."
