#!/bin/bash
# Pommedoro Installer
# Double-click this file to install Pommedoro to /Applications

set -euo pipefail

APP_NAME="Pommedoro"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_SRC="${SCRIPT_DIR}/${APP_NAME}.app"
APP_DST="/Applications/${APP_NAME}.app"

echo ""
echo "  Installing ${APP_NAME}..."
echo ""

if [ ! -d "${APP_SRC}" ]; then
    echo "  ERROR: ${APP_NAME}.app not found next to this installer."
    echo "  Make sure the DMG is mounted and try again."
    echo ""
    read -n 1 -s -r -p "  Press any key to close..."
    exit 1
fi

# Stop running instance if any
pkill -9 -f "${APP_NAME}" 2>/dev/null || true
sleep 0.3

# Copy to /Applications
rm -rf "${APP_DST}"
cp -R "${APP_SRC}" "${APP_DST}"

# Strip quarantine attribute (fixes "app is damaged" on downloaded DMGs)
xattr -cr "${APP_DST}"

# Stamp SHA256 so auto-updater knows current version
SHA_DIR="${HOME}/Library/Application Support/Pommedoro"
mkdir -p "${SHA_DIR}"
# Find the source .dmg backing this mounted volume
DMG_DEVICE="$(hdiutil info 2>/dev/null | grep -B 20 "${SCRIPT_DIR}" | grep 'image-path' | awk -F' : ' '{print $2}' | head -1)"
if [ -n "${DMG_DEVICE}" ] && [ -f "${DMG_DEVICE}" ]; then
    shasum -a 256 "${DMG_DEVICE}" | awk '{print $1}' > "${SHA_DIR}/current.sha256"
    echo "  SHA256 stamped for auto-update."
fi

echo "  Installed to ${APP_DST}"
echo "  Launching ${APP_NAME}..."
echo ""

open "${APP_DST}"

echo "  Done!"
echo ""
