# SPDX-FileCopyrightText: 2020 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ depot, pkgs, ... }:
pkgs.writeShellScriptBin "switch-prebuilt" ''
  set -ue

  export AWS_ACCESS_KEY_ID="${depot.ops.secrets.nixCache.AWS_ACCESS_KEY_ID}"
  export AWS_SECRET_ACCESS_KEY="${depot.ops.secrets.nixCache.AWS_SECRET_ACCESS_KEY}"
  system="''${1}"

  if [[ ! -e "$system" ]]; then
    # We should be a trusted-user.
    nix copy -v --from 's3://lukegb-nix-cache?endpoint=storage.googleapis.com' --no-check-sigs "$system"
  fi

  diff "$system/etc/hostname" "/etc/hostname"

  # The next phase requires sudo, but it's harmless to run the preceding commands twice.
  if [[ $EUID -ne 0 ]]; then
    exec sudo "$0" "$@"
  fi

  nix-env -p /nix/var/nix/profiles/system --set "$system"
  "$system/bin/switch-to-configuration" switch
''