#!/usr/bin/env bash

# omarchy:summary=Install VS Code and configure Omarchy defaults for secrets, updates, and theme
# omarchy:requires-sudo=true

# Based: VS Code comes from Flathub on Debian and from its cask on macOS,
# then the editor defaults the former dev tooling carried land where this
# OS's VS Code reads them: settings.json and keybindings.json, and on Debian
# upstream's argv.json secret store, updater switch and Omarchy theme. The
# Mac keeps the cask's own updater and the Keychain.

set -eo pipefail

echo "Installing VSCode..."
omarchy-pkg-add code flatpak=com.visualstudio.code cask=visual-studio-code

user_dir=$(omarchy-code-config-dir code)
mkdir -p "$user_dir"
[[ -e $user_dir/keybindings.json ]] || cp "$OMARCHY_PATH/config/code/User/keybindings.json" "$user_dir/keybindings.json"
[[ -e $user_dir/settings.json ]] || cp "$OMARCHY_PATH/config/code/User/settings.json" "$user_dir/settings.json"

if [[ $(omarchy-os) != darwin ]]; then
  mkdir -p ~/.vscode
  cat >~/.vscode/argv.json <<'ARGV'
// This configuration file allows you to pass permanent command line arguments to VS Code.
// Only a subset of arguments is currently supported to reduce the likelihood of breaking
// the installation.
//
// PLEASE DO NOT CHANGE WITHOUT UNDERSTANDING THE IMPACT
//
// NOTE: Changing this file requires a restart of VS Code.
{
  "password-store":"gnome-libsecret"
}
ARGV

  # Ensure VSC's own auto-update feature is turned off
  if omarchy-cmd-present jq; then
    tmp=$(mktemp)
    jq '. + {"update.mode": "none"}' "$user_dir/settings.json" >"$tmp" && mv "$tmp" "$user_dir/settings.json"
  fi

  # Apply Omarchy theme to VSCode
  omarchy-theme-set-vscode || true
fi

omarchy-code-extensions ahmadalli.vscode-nginx-conf eamodio.gitlens editorconfig.editorconfig gruntfuggly.todo-tree \
  kisstkondoros.vscode-gutter-preview mechatroner.rainbow-csv mikestead.dotenv mkhl.direnv ms-vscode.hexeditor \
  ms-vscode.makefile-tools ms-python.python naumovs.color-highlight psioniq.psi-header redhat.vscode-xml redhat.vscode-yaml \
  streetsidesoftware.code-spell-checker ultram4rine.vscode-choosealicense vscodevim.vim vspacecode.vspacecode \
  vspacecode.whichkey zawys.vscode-as-git-mergetool

if [[ $(omarchy-os) == darwin ]]; then
  open -a "Visual Studio Code" >/dev/null 2>&1 || true
  exit 0
fi
setsid uwsm-app -- gtk-launch code >/dev/null 2>&1 &
