#!/usr/bin/env nix-shell
#!nix-shell -i bash -p git gnupg

export IN_NIX_SHELL=

set -ex

mkdir -p /mnt/home/balsoft/projects
nixos-generate-config --root /mnt
echo import /home/balsoft/projects/nixos-config \"$(hostname)\" > /mnt/etc/nixos/configuration.nix
cd /mnt/home/balsoft/projects
[ -d nixos-config ] || git clone ssh://git@github.com/balsoft/nixos-config
cd nixos-config

touch secret.nix
while [[ ! -s secret.nix ]]
do gpg -dq secret.nix.gpg > secret.nix
done

[ -s hardware-configuration/$(hostname).nix ] || mv /mnt/etc/nixos/hardware-configuration.nix hardware-configuration/$(hostname).nix

mkdir -p /home/balsoft
mount --rbind /mnt/home/balsoft /home/balsoft
mount --rbind /mnt/etc/nixos /etc/nixos

export NIX_PATH=

nixpkgs=$(nix eval --raw '(import ./nix/sources.nix).nixpkgs')
nix-store --repair-path $nixpkgs # Evaluating doesn't actually add it to store
rm /tmp/nixpkgs -rf
cp -r $nixpkgs /tmp/nixpkgs # Because we lose everything we added to store after we unmount it

export NIX_PATH=nixpkgs=/tmp/nixpkgs:nixos-config=/etc/nixos/configuration.nix

nix copy --all --to /mnt --no-require-sigs

echo The following operation is irreversible. RET to continue.
read

umount -l /nix/.rw-store || echo "RW-store is not mounted."
mount --rbind /mnt/nix /nix

nix build -f /tmp/nixpkgs/nixos system --substituters "https://cache.balsoft.ru https://cache.nixos.org" --no-require-sigs
nixos-install --system ./result
cd /mnt/home/balsoft
chmod 777 -R .
