#!/bin/bash
set -e

config_dir="$XDG_CONFIG_HOME"
if [ -z "$config_dir" ]; then
  config_dir="$HOME/.config"
fi

default_ini="$config_dir/compiz-1/compizconfig/Default.ini"

if [ -f "$default_ini" ]; then
  rm "$default_ini"
fi

compiz_profile="ubuntu"
settings_profile="unity"
supports_3d=true

if ! /usr/lib/nux/unity_support_test -p; then
  supports_3d=false
fi

if [ "$UNITY_LOW_GFX_MODE" != 0 ]; then
  if [ "$supports_3d" == false ] ||
     [ "$(gsettings get com.canonical.Unity lowgfx)" == "true" ]; then
    settings_profile="unity-lowgfx"
  fi
fi

echo "Using compiz profile '$compiz_profile:$settings_profile'"

export COMPIZ_CONFIG_PROFILE="$compiz_profile"
export UNITY_HAS_3D_SUPPORT="$supports_3d"
export UNITY_DEFAULT_PROFILE="$settings_profile"

if [ -n "$UPSTART_SESSION" ]; then
  initctl set-env -g COMPIZ_CONFIG_PROFILE=$COMPIZ_CONFIG_PROFILE
  initctl set-env -g UNITY_HAS_3D_SUPPORT=$UNITY_HAS_3D_SUPPORT
  initctl set-env -g UNITY_DEFAULT_PROFILE=$UNITY_DEFAULT_PROFILE
else
  update_env_args="--systemd"
fi

dbus-update-activation-environment $update_env_args --verbose COMPIZ_CONFIG_PROFILE
dbus-update-activation-environment $update_env_args --verbose UNITY_HAS_3D_SUPPORT
dbus-update-activation-environment $update_env_args --verbose UNITY_DEFAULT_PROFILE

@UNITY_LIBDIR@/compiz-config-profile-setter $settings_profile
@UNITY_LIBDIR@/unity-active-plugins-safety-check
