#!/usr/bin/env bash
set -euo pipefail

APP_NAME="CAG POS"
APP_PATH="/Applications/${APP_NAME}.app"
VERSION="${CAG_POS_VERSION:-}"
BASE_URL="${CAG_POS_BASE_URL:-https://cag.mybusinesslife.fr/cag-pos}"
WORK_DIR="${TMPDIR:-/tmp}/cag-pos-mac-test-install"

arch="$(uname -m)"

rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR"

if [[ -z "$VERSION" ]]; then
  echo "Lecture de la derniere version Mac publiee..."
  curl -fsSL "$BASE_URL/latest-mac.yml" -o "$WORK_DIR/latest-mac.yml"
  VERSION="$(sed -n "s/^version:[[:space:]]*['\"]*\\([^'\"]*\\)['\"]*$/\\1/p" "$WORK_DIR/latest-mac.yml" | head -n 1)"
fi

if [[ -z "$VERSION" ]]; then
  echo "Version Mac introuvable dans latest-mac.yml."
  exit 1
fi

case "$arch" in
  arm64)
    artifact="${APP_NAME}-${VERSION}-mac-arm64.zip"
    ;;
  x86_64)
    artifact="${APP_NAME}-${VERSION}-mac-x64.zip"
    ;;
  *)
    echo "Architecture Mac non supportee: ${arch}"
    exit 1
    ;;
esac

url="${BASE_URL}/${artifact// /%20}"

echo "Installation test ${APP_NAME} ${VERSION}"
echo "Architecture detectee: ${arch}"
echo "Telechargement: ${url}"
echo ""

curl -fL "$url" -o "$WORK_DIR/${artifact}"
ditto -x -k "$WORK_DIR/${artifact}" "$WORK_DIR/unpacked"

src_app="$(find "$WORK_DIR/unpacked" -maxdepth 2 -name "${APP_NAME}.app" -type d | head -n 1)"
if [[ -z "$src_app" || ! -d "$src_app" ]]; then
  echo "Application introuvable dans l'archive telechargee."
  exit 1
fi

echo ""
echo "Installation dans ${APP_PATH}"
if [[ -d "$APP_PATH" ]]; then
  sudo rm -rf "$APP_PATH"
fi
sudo ditto "$src_app" "$APP_PATH"

echo "Retrait des attributs macOS de telechargement"
sudo xattr -cr "$APP_PATH"

echo "Resignature locale ad-hoc pour test"
sudo codesign --force --deep --sign - "$APP_PATH"
sudo codesign --verify --deep --strict --verbose=2 "$APP_PATH"

echo "Ajout d'une autorisation Gatekeeper locale de test"
sudo spctl --add --label "CAG POS Test" "$APP_PATH" 2>/dev/null || true

echo ""
echo "Ouverture de ${APP_NAME}"
open "$APP_PATH"

echo ""
echo "Termine. Cette installation est uniquement pour test interne."
echo "Pour les equipes, il faudra une version signee/notarisee Apple."
