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

source "${HOME}/.local/opt/codex-desktop-linux/lib/codex-desktop-linux/common.sh"

ensure_layout
load_install_config
load_metadata

exec 9>"$STATE_DIR/update.lock"
flock 9

quiet=0
force=0
record_only=0

while [ $# -gt 0 ]; do
    case "$1" in
        --quiet)
            quiet=1
            ;;
        --force)
            force=1
            ;;
        --record-only)
            record_only=1
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 2
            ;;
    esac
    shift
done

log() {
    if [ "$quiet" -eq 0 ]; then
        echo "$@"
    fi
}

if [ "$record_only" -eq 1 ]; then
    # Icon extraction is best-effort: without a usable cached Codex.dmg it
    # must not abort metadata recording under set -e.
    extract_icon || log "Icon extraction skipped: no usable cached Codex.dmg."
    record_metadata
    log "Metadata refreshed."
    exit 0
fi

build_head="${REPO_HEAD-}"
if [ -z "$build_head" ]; then
    build_head="$(current_repo_head)"
fi
source_overlay_sha="$(source_repo_overlay_signature 2>/dev/null || true)"
remote_head=""
dmg_headers=""

if ! remote_head="$(remote_repo_head 2>/dev/null)"; then
    echo "Could not query wrapper repo upstream." >&2
    exit 1
fi

if ! dmg_headers="$(remote_dmg_headers 2>/dev/null)"; then
    echo "Could not query Codex.dmg headers." >&2
    exit 1
fi

remote_etag="$(header_value "$dmg_headers" "etag")"
remote_last_modified="$(header_value "$dmg_headers" "last-modified")"
remote_content_length="$(header_value "$dmg_headers" "content-length")"
remote_dmg_identity_reliable=0
if [ -n "$remote_etag" ] || \
   { [ -n "$remote_last_modified" ] && [ -n "$remote_content_length" ]; }; then
    remote_dmg_identity_reliable=1
fi

repo_changed=0
dmg_changed=0
repo_upstream_changed=0
repo_overlay_changed=0
app_missing=0

if [ ! -x "$APP_DIR/start.sh" ]; then
    app_missing=1
fi

if [ "$build_head" != "$remote_head" ]; then
    repo_changed=1
    repo_upstream_changed=1
fi

if [ "$source_overlay_sha" != "${SOURCE_OVERLAY_SHA256-}" ]; then
    repo_changed=1
    repo_overlay_changed=1
fi

if [ "$force" -eq 1 ] || [ "$remote_dmg_identity_reliable" -eq 0 ] || \
   [ "${DMG_ETAG-}" != "$remote_etag" ] || \
   [ "${DMG_LAST_MODIFIED-}" != "$remote_last_modified" ] || \
   [ "${DMG_CONTENT_LENGTH-}" != "$remote_content_length" ]; then
    dmg_changed=1
fi

if [ "$repo_changed" -eq 0 ] && [ "$dmg_changed" -eq 0 ] && \
   [ "$force" -eq 0 ] && [ "$app_missing" -eq 0 ]; then
    log "ChatGPT Desktop wrapper is already up to date."
    exit 0
fi

if [ "$app_missing" -eq 1 ]; then
    log "Installed app is missing; rebuilding wrapper..."
fi

prepare_build_repo

if [ "$repo_changed" -eq 1 ]; then
    if [ "$repo_upstream_changed" -eq 1 ]; then
        log "Refreshing wrapper repo in managed build checkout..."
    fi
    if [ "$repo_overlay_changed" -eq 1 ]; then
        log "Applying source repo overlay changes..."
    fi
    if [ -x "$BUILD_REPO_DIR/contrib/user-local-install/install-user-local.sh" ]; then
        log "Refreshing installed helper scripts..."
        CODEX_USER_LOCAL_SOURCE_REPO_DIR="$SOURCE_REPO_DIR" \
            "$BUILD_REPO_DIR/contrib/user-local-install/install-user-local.sh" --from-update
        load_install_config
        load_metadata
    fi
fi

if [ "$dmg_changed" -eq 1 ]; then
    log "Refreshing cached Codex.dmg..."
    dmg_file="$(cached_dmg_file)"
    rm -f "$dmg_file" "$dmg_file.metadata"
fi

log "Rebuilding wrapper..."
(
    cd "$BUILD_REPO_DIR"
    mkdir -p "$STATE_DIR/tmp"
    # Honor a caller-provided feature config (e.g. the in-app Update button's
    # feature picker) over the repo-local default, so a picked selection wins.
    if [ -z "${CODEX_LINUX_FEATURES_CONFIG:-}" ] && \
       [ -f "$SOURCE_REPO_DIR/linux-features/features.json" ]; then
        export CODEX_LINUX_FEATURES_CONFIG="$SOURCE_REPO_DIR/linux-features/features.json"
    fi
    TMPDIR="$STATE_DIR/tmp" \
    CODEX_ACCEPTANCE_OVERRIDE=0 \
    CODEX_INSTALL_ALLOW_RUNNING=0 \
        CODEX_INSTALL_ROOT="$OPT_ROOT" \
        CODEX_INSTALL_DIR="$APP_DIR" \
        ./install.sh
)

extract_icon || log "Icon extraction skipped: no usable cached Codex.dmg."
record_metadata

if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "${XDG_DATA_HOME}/applications" >/dev/null 2>&1 || true
fi

log "Update complete."
