#!/bin/sh
set -eu

SCRIPT_PATH="$0"
case "$SCRIPT_PATH" in
  /*) ;;
  *) SCRIPT_PATH="$(command -v "$0")" ;;
esac
APP_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
LOG_FILE="$APP_DIR/data/deploy.log"
LOCK_DIR="$APP_DIR/data/deploy.lock"

mkdir -p "$APP_DIR/data"

if ! mkdir "$LOCK_DIR" 2>/dev/null; then
  echo "$(date '+%Y-%m-%d %H:%M:%S') deploy already running" >> "$LOG_FILE"
  exit 0
fi
trap 'rmdir "$LOCK_DIR"' EXIT

cd "$APP_DIR"

echo "$(date '+%Y-%m-%d %H:%M:%S') deploy start" >> "$LOG_FILE"
git -c credential.helper="store --file=/var/services/homes/whitekomani/.git-credentials" fetch origin main >> "$LOG_FILE" 2>&1
git reset --hard origin/main >> "$LOG_FILE" 2>&1

/usr/local/bin/docker build -t photoreq:latest . >> "$LOG_FILE" 2>&1
./run.sh >> "$LOG_FILE" 2>&1

echo "$(date '+%Y-%m-%d %H:%M:%S') deploy done $(git rev-parse --short HEAD)" >> "$LOG_FILE"
