summary refs log tree commit diff
path: root/pkgs/build-support/vm/windows/bootstrap.nix
blob: 47afce5b5a379ebe10b0c9015736615bde57a6b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
{ stdenv, fetchurl, vmTools, writeScript, writeText, runCommand, makeInitrd
, python, perl, coreutils, dosfstools, gzip, mtools, netcat, openssh, qemu
, samba, socat, vde2, cdrkit, pathsFromGraph
}:

{ isoFile, productKey, arch ? null }:

with stdenv.lib;

let
  controller = import ./controller {
    inherit stdenv writeScript vmTools makeInitrd;
    inherit samba vde2 openssh socat netcat coreutils gzip;
  };

  mkCygwinImage = import ./cygwin-iso {
    inherit stdenv fetchurl runCommand python perl cdrkit pathsFromGraph;
    arch = let
      defaultArch = if stdenv.is64bit then "x86_64" else "i686";
    in if arch == null then defaultArch else arch;
  };

  installer = import ./install {
    inherit controller mkCygwinImage;
    inherit stdenv runCommand openssh qemu writeText dosfstools mtools;
  };
in rec {
  installedVM = installer {
    inherit isoFile productKey;
  };

  runInVM = img: attrs: controller (attrs // {
    inherit (installedVM) sshKey;
    qemuArgs = attrs.qemuArgs or [] ++ [
      "-boot order=c"
      "-drive file=${img},index=0,media=disk"
    ];
  });

  runAndSuspend = let
    drives = {
      s = {
        source = "nixstore";
        target = "/nix/store";
      };
      x = {
        source = "xchg";
        target = "/tmp/xchg";
      };
    };

    genDriveCmds = letter: { source, target }: [
      "net use ${letter}: '\\\\192.168.0.2\\${source}' /persistent:yes"
      "mkdir -p '${target}'"
      "mount -o bind '/cygdrive/${letter}' '${target}'"
      "echo '/cygdrive/${letter} ${target} none bind 0 0' >> /etc/fstab"
    ];
  in runInVM "winvm.img" {
    command = concatStringsSep " && " ([
      "net config server /autodisconnect:-1"
    ] ++ concatLists (mapAttrsToList genDriveCmds drives));
    suspendTo = "state.gz";
  };

  suspendedVM = stdenv.mkDerivation {
    name = "cygwin-suspended-vm";
    buildCommand = ''
      ${qemu}/bin/qemu-img create \
        -b "${installedVM}/disk.img" \
        -f qcow2 winvm.img
      ${runAndSuspend}
      ensureDir "$out"
      cp winvm.img "$out/disk.img"
      cp state.gz "$out/state.gz"
    '';
  };

  resumeAndRun = command: runInVM "${suspendedVM}/disk.img" {
    resumeFrom = "${suspendedVM}/state.gz";
    qemuArgs = singleton "-snapshot";
    inherit command;
  };
}