SERVICES=("bluetooth" "scx_loader")

update_user() {
  # Get user name and update it in config files.
  export LANG=C
  if usr=$(id -nu 1000) && [[ ! -z ${usr} ]]; then
     echo "Setting ${usr} as name for autologin and decky environment variables."
  elif usr=$(id -nu 1001) && [[ ! -z ${usr} ]]; then
     echo "Setting ${usr} as name for autologin and decky environment variables."
  else
     echo "Get user name failed, setting 'User=' in /etc/plasmalogin.conf.d/steam-deckify.conf"
  fi
  # Autologin
  sed -ri "s|^(User=).*|User=${usr}|" /etc/plasmalogin.conf.d/steam-deckify.conf
  # Decky loader
  sed -ri "s|^(DECKY_USER=).*|DECKY_USER=${usr}|" /etc/environment.d/handheld.conf
  sed -ri "s|^(DECKY_USER_HOME=).*|DECK_USER_HOME=/home/${usr}|" /etc/environment.d/handheld.conf

  # Return to Gaming Mode file
  cp /etc/skel/Desktop/steamos-gamemode.desktop /home/${usr}/Desktop/steamos-gamemode.desktop
}

scx_lavd_default() {
  # migrate all users to scx_loader
  local config_path="/etc/scx_loader.toml"
  if [[ ! -f "$config_path" ]]; then
     cat <<'EOF' > "$config_path"
default_sched = "scx_lavd"
EOF
  fi
}

post_install() {
  # Use scx_lavd as default scheduler
  scx_lavd_default

  echo "Enabling services..."
  for service in "${SERVICES[@]}"; do
    systemctl enable "$service" --now
  done

  # Enable Plasma Login Manager
  ln -sf /usr/lib/systemd/system/plasmalogin.service /etc/systemd/system/display-manager.service

  # First boot setup
  touch /etc/handheld-first-boot

  # Update users plasmalogin config to reflect the changes
  echo "Updating Handheld Configs."
  update_user
  # echo "If you are installing this without the CachyOS Installation, please update your username in the /etc/plasmalogin.conf.d/*"
}

pre_upgrade() {
  rm -f /etc/limine-entry-tool.d/20-chwd.conf
}

post_upgrade() {
  # Use scx_lavd as default scheduler
  scx_lavd_default

  # Enable Plasma Login Manager
  ln -sf /usr/lib/systemd/system/plasmalogin.service /etc/systemd/system/display-manager.service

  # Update files to reflect the changes
  echo "Updating Handheld Configs."
  update_user
}
