#!/bin/bash

CURRENT_DIR=$(realpath $(dirname $0))
NEEDS_SUDO=0
SUDO=""
DOCKER_TAG="lastres:latest"
DOCKER_BUILD_PARAMS="$CURRENT_DIR -t $DOCKER_TAG"
DOCKER_RUN_PARAMS="run -it -v /var/run/postgresql/:/var/run/postgresql/ -v $CURRENT_DIR:/var/lib/las_tres/LasTres -v /var/run/redis/:/var/run/redis --name LasTresDocker -p 3000:3000 $DOCKER_TAG"
CHECKSUM_DOCKER_FILE="$CURRENT_DIR/.dockerfile_checksum"

OLD_CHECKSUM_DOCKER="$(cat $CHECKSUM_DOCKER_FILE 2> /dev/null)"
perl -pe 's/\{\{UID\}\}/'"$UID/" Dockerfile.template > Dockerfile
CURRENT_CHECKSUM_DOCKER="$(sha512sum Dockerfile | awk '{ print $1 }')"

if ! [ -f las_tres.yml ]; then
    cat << EOF > las_tres.yml
secrets:
  - $(pwgen -s 512 1)
database:
  user: $(whoami)
  dbname: las_tres 
hypnotoad:
  listen:
    - http://*:3000
EOF
fi &&
if ! docker image ls 2>/dev/null; then
    NEEDS_SUDO=1
fi

if [[ $NEEDS_SUDO -gt 0 ]]; then
    SUDO="sudo"
fi

if [[ $OLD_CHECKSUM_DOCKER != $CURRENT_CHECKSUM_DOCKER ]]; then
    echo "$OLD_CHECKSUM_DOCKER != $CURRENT_CHECKSUM_DOCKER rebuilding docker";

    echo $SUDO docker container rm LasTresDocker
    $SUDO docker container rm LasTresDocker ;
    echo $SUDO docker build $DOCKER_BUILD_PARAMS
    $SUDO docker build $DOCKER_BUILD_PARAMS
    echo $CURRENT_CHECKSUM_DOCKER > $CHECKSUM_DOCKER_FILE
    echo $SUDO docker $DOCKER_RUN_PARAMS
    $SUDO docker $DOCKER_RUN_PARAMS
    exit
fi
echo $SUDO docker container start LasTresDocker -ai
if ! $SUDO docker container start LasTresDocker -ai; then
    echo $SUDO docker $DOCKER_RUN_PARAMS
    $SUDO docker $DOCKER_RUN_PARAMS
fi
