#!/bin/sh
set -eu

cd /work
rm -rf /work/unidesk

/etc/unidesk-cicd-branch-follower/sync-source.sh \
  "${UNIDESK_CONTROLLER_SOURCE_REPOSITORY}" \
  "${UNIDESK_CONTROLLER_SOURCE_BRANCH}" \
  "${UNIDESK_CONTROLLER_SOURCE_SNAPSHOT_PREFIX}" \
  "/cache/${UNIDESK_CONTROLLER_SOURCE_REPOSITORY}.git"

git clone --branch "${UNIDESK_CONTROLLER_SOURCE_BRANCH}" "/cache/${UNIDESK_CONTROLLER_SOURCE_REPOSITORY}.git" /work/unidesk
cp /etc/unidesk-cicd-branch-follower/cicd-branch-followers.yaml /work/unidesk/config/cicd-branch-followers.yaml
cd /work/unidesk

machine_output=false
for arg in "$@"; do
  case "$arg" in
    --json|--raw|json)
      machine_output=true
      ;;
  esac
done

if [ "${machine_output}" = true ]; then
  output_file=$(mktemp)
  if "$@" >"${output_file}"; then
    node - "${output_file}" <<'NODE'
const { readFileSync } = require("node:fs");
const path = process.argv[2];
const text = readFileSync(path, "utf8").trim();
if (text.length === 0) process.exit(0);
try {
  process.stdout.write(JSON.stringify(JSON.parse(text)));
} catch {
  process.stdout.write(text);
}
NODE
  else
    status=$?
    cat "${output_file}"
    exit "${status}"
  fi
else
  "$@"
fi
