<commit_before>#! @shell@

# - make Nix store etc.
# - copy closure of Nix to target device
# - register validity
# - with a chroot to the target device:
#   * nix-env -p /nix/var/nix/profiles/system -i <nix-expr for the configuration>
#   * install the boot loader

# Ensure a consistent umask.
umask 0022

# Create FHS for Triton relative to mountpoint ($1).
create_triton_fhs() {
  local -A -r directories=(
    ['bin']='0755'  # /bin/sh
    ['dev']='0755'
    ['etc']='0755'
    ['etc/ssl']='0755'
    ['etc/ssl/certs']='0755'
    ['home']='0755'
    ['nix']='0755'
    ['nix/store']='1775'
    ['nix/var']='0755'
    ['nix/var/log']='0755'
    ['nix/var/log/nix']='0755'
    ['nix/var/log/nix/drvs']='0755'
    ['nix/var/nix']='0755'
    ['nix/var/nix/db']='0755'
    ['nix/var/nix/gcroots']='0755'
    ['nix/var/nix/manifests']='0755'
    ['nix/var/nix/profiles']='0755'
    ['nix/var/nix/profiles/per-user']='1777'
    ['nix/var/nix/profiles/per-user/root']='0755'
    ['nix/var/nix/temproots']='0755'
    ['nix/var/userpool']='0755'
    ['proc']='0755'
    ['root']='0700'
    ['root/.nix-defexpr']='0700'
    ['run']='0755'
    ['sys']='0755'
    ['tmp']='01777'
    ['tmp/root']='0755'
    ['usr']='0755'
    ['usr/bin']='0755'  # /usr/bin/env
    ['var']='0755'
    ['var/setuid-wrappers']='0755'
  )
  local directory
  local -r mount_point="${1}"

  # Create directory structure relative to $mount_point.
  for directory in "${!directories[@]}"; do
    if [ -d "${mount_point}/${directory}" ]; then
      chown --verbose "${directories["${directory}"]}" \
        "${mount_point}/${directory}" || {
          echo "ERROR: failed to set permissions for directory: ${mount_point}/${directory}" >&2
          return 1
        }
    else
      # Do NOT specify --parents to make sure the directory structure is
      # unrolled correctly.  Instead specify the parent directories in
      # the array above so that the structure is created with the correct
      # permissions.
      mkdir \
        --verbose \
        --mode="${directories["${directory}"]}" \
        "${mount_point}/${directory}" || {
          echo "ERROR: failed to create directory: ${mount_point}/${directory}" >&2
          return 1
        }
    fi
  done
}

copy_host_file() {
  local -r destination_file="${3}"
  local file
  local -r mount_point="${1}"
  local -r permissions="${2}"
  shift 3
  local -a -r source_files=("$@")

  if [ -f "${mount_point}/${destination_file}" ]; then
    rm --force --verbose "${mount_point}/${destination_file}"
  fi

  # Always assume destination location is a source
  source_files+=("${destination_file}")

  for file in "${source_files[@]}"; do
    if [ -f "/${file}"]; then
      cp --dereference --force --verbose "/${file}" \
        "${mount_point}/${destination_file}"
      chown "${permissions}" "${mount_point}/${destination_file}"
    fi
  done
}

# Re-exec ourselves in a private mount namespace so that our bind
# mounts get cleaned up automatically.
if [ $(id -u) -eq 0 ]; then
  if [ -z "$NIXOS_INSTALL_REEXEC" ]; then
    export NIXOS_INSTALL_REEXEC=1
    exec unshare --mount --uts -- "$0" "$@"
  else
    mount --verbose --make-rprivate '/'
  fi
fi

# Parse the command line for the -I flag
extraBuildFlags=()
chrootCommand=('/run/current-system/sw/bin/bash')
buildUsersGroup='nixbld'

while [ "$#" -gt 0 ]; do
  i="$1"; shift 1
  case "$i" in
    '--max-jobs'|'-j'|'--cores'|'-I')
      j="$1"; shift 1
      extraBuildFlags+=("$i" "$j")
      ;;
    '--option')
      j="$1"; shift 1
      k="$1"; shift 1
      extraBuildFlags+=("$i" "$j" "$k")
      ;;
    '--root')
      MOUNT_POINT="$1"; shift 1
      ;;
    '--closure')
      closure="$1"; shift 1
      buildUsersGroup=""
      ;;
    '--no-channel-copy')
      noChannelCopy=1
      ;;
    '--no-root-passwd')
      noRootPasswd=1
      ;;
    '--no-bootloader')
      noBootLoader=1
      ;;
    '--show-trace')
      extraBuildFlags+=("$i")
      ;;
    '--chroot')
      runChroot=1
      if [ ! -z "$@" ]; then
        chrootCommand=("$@")
      fi
      break
      ;;
    '--help')
      exec man nixos-install
      exit 1
      ;;
    *)
      echo "$0: unknown option \`$i'" >&2
      exit 1
      ;;
  esac
done

set -e
shopt -s nullglob

declare -r MOUNT_POINT="${MOUNT_POINT:-/mnt}"

if ! test -e "$MOUNT_POINT"; then
  echo "mount point $MOUNT_POINT doesn't exist" >&2
  exit 1
fi

create_triton_fhs "${MOUNT_POINT}"

copy_host_file "${MOUNT_POINT}" '0644' 'etc/hosts'
copy_host_file "${MOUNT_POINT}" '0644' 'etc/resolv.conf'
copy_host_file "${MOUNT_POINT}" '0644' 'etc/ssl/certs/ca-certificates.crt' \
  'etc/ssl/certs/ca-bundle.crt'

# Mount some stuff in the target root directory.
mount --verbose --rbind '/dev' "$MOUNT_POINT/dev"
mount --verbose --rbind '/proc' "$MOUNT_POINT/proc"
mount --verbose --rbind '/sys' "$MOUNT_POINT/sys"
mount --verbose --rbind '/' "$MOUNT_POINT/tmp/root"
mount --verbose --types tmpfs --options 'mode=0755' none "$MOUNT_POINT/run"
mount --verbose --types tmpfs --options 'mode=0755' none \
  "$MOUNT_POINT/var/setuid-wrappers"
rm --verbose --recursive --force "$MOUNT_POINT/var/run"
ln --verbose --symbolic '/run' "$MOUNT_POINT/var/run"
for f in '/etc/passwd' '/etc/group'; do
  touch "$MOUNT_POINT/$f"
  if [ -f "$f" ]; then
    mount --rbind --options ro "$f" "$MOUNT_POINT/$f"
  fi
done

if [ -n "$runChroot" ]; then
  if ! [ -L "$MOUNT_POINT/nix/var/nix/profiles/system" ]; then
    echo "$0: installation not finished; cannot chroot into installation directory" >&2
    exit 1
  fi
  ln --verbose --symbolic \
    '/nix/var/nix/profiles/system' "$MOUNT_POINT/run/current-system"
  exec chroot "$MOUNT_POINT" "${chrootCommand[@]}"
fi

# Get the path of the NixOS configuration file.
if test -z "$NIXOS_CONFIG"; then
  NIXOS_CONFIG='/etc/nixos/configuration.nix'
fi

if [ ! -e "$MOUNT_POINT/$NIXOS_CONFIG" ] && [ -z "$closure" ]; then
  echo "configuration file $MOUNT_POINT/$NIXOS_CONFIG doesn't exist" >&2
  exit 1
fi

chown @root_uid@:@nixbld_gid@ "$MOUNT_POINT/nix/store"

# There is no daemon in the chroot.
unset NIX_REMOTE
<commit_msg>nixos-install.sh: simplify rbind mounts of files and directories<commit_after>#! @shell@

# - make Nix store etc.
# - copy closure of Nix to target device
# - register validity
# - with a chroot to the target device:
#   * nix-env -p /nix/var/nix/profiles/system -i <nix-expr for the configuration>
#   * install the boot loader

# Ensure a consistent umask.
umask 0022

# Create FHS for Triton relative to mountpoint ($1).
create_triton_fhs() {
  local -A -r directories=(
    ['bin']='0755'  # /bin/sh
    ['dev']='0755'
    ['etc']='0755'
    ['etc/ssl']='0755'
    ['etc/ssl/certs']='0755'
    ['home']='0755'
    ['nix']='0755'
    ['nix/store']='1775'
    ['nix/var']='0755'
    ['nix/var/log']='0755'
    ['nix/var/log/nix']='0755'
    ['nix/var/log/nix/drvs']='0755'
    ['nix/var/nix']='0755'
    ['nix/var/nix/db']='0755'
    ['nix/var/nix/gcroots']='0755'
    ['nix/var/nix/manifests']='0755'
    ['nix/var/nix/profiles']='0755'
    ['nix/var/nix/profiles/per-user']='1777'
    ['nix/var/nix/profiles/per-user/root']='0755'
    ['nix/var/nix/temproots']='0755'
    ['nix/var/userpool']='0755'
    ['proc']='0755'
    ['root']='0700'
    ['root/.nix-defexpr']='0700'
    ['run']='0755'
    ['sys']='0755'
    ['tmp']='01777'
    ['tmp/root']='0755'
    ['usr']='0755'
    ['usr/bin']='0755'  # /usr/bin/env
    ['var']='0755'
    ['var/setuid-wrappers']='0755'
  )
  local directory
  local -r mount_point="${1}"

  # Create directory structure relative to $mount_point.
  for directory in "${!directories[@]}"; do
    if [ -d "${mount_point}/${directory}" ]; then
      chown --verbose "${directories["${directory}"]}" \
        "${mount_point}/${directory}" || {
          echo "ERROR: failed to set permissions for directory: ${mount_point}/${directory}" >&2
          return 1
        }
    else
      # Do NOT specify --parents to make sure the directory structure is
      # unrolled correctly.  Instead specify the parent directories in
      # the array above so that the structure is created with the correct
      # permissions.
      mkdir \
        --verbose \
        --mode="${directories["${directory}"]}" \
        "${mount_point}/${directory}" || {
          echo "ERROR: failed to create directory: ${mount_point}/${directory}" >&2
          return 1
        }
    fi
  done
}

copy_host_file() {
  local -r destination_file="${3}"
  local file
  local -r mount_point="${1}"
  local -r permissions="${2}"
  shift 3
  local -a -r source_files=("$@")

  if [ -f "${mount_point}/${destination_file}" ]; then
    rm --force --verbose "${mount_point}/${destination_file}"
  fi

  # Always assume destination location is a source
  source_files+=("${destination_file}")

  for file in "${source_files[@]}"; do
    if [ -f "/${file}"]; then
      cp --dereference --force --verbose "/${file}" \
        "${mount_point}/${destination_file}"
      chown "${permissions}" "${mount_point}/${destination_file}"
      break
    fi
  done
}

rbind_host_dir() {
  local -r destination_dir="${2}"
  local dir
  local -r mount_point="${1}"
  shift 2
  local -a -r source_dirs=("$@")

  # Always assume destination location is a source
  source_dirs+=("${destination_dir}")

  for dir in "${source_dirs[@]}"; do
    if [ -d "/${dir}"]; then
      mount --verbose --rbind "/${dir}" \
        "${mount_point}/${destination_dir}"
      break
    fi
  done
}

rbind_host_file() {
  local -r destination_file="${2}"
  local file
  local -r mount_point="${1}"
  shift 2
  local -a -r source_files=("$@")

  if [ -f "${mount_point}/${destination_file}" ]; then
    rm --force --verbose "${mount_point}/${destination_file}"
  fi

  # Always assume destination location is a source
  source_files+=("${destination_file}")

  for file in "${source_files[@]}"; do
    if [ -f "/${file}"]; then
      touch "${mount_point}/${destination_file}"
      mount --verbose --rbind --options ro "/${file}" \
        "${mount_point}/${destination_file}"
      break
    fi
  done
}

# Re-exec ourselves in a private mount namespace so that our bind
# mounts get cleaned up automatically.
if [ $(id -u) -eq 0 ]; then
  if [ -z "$NIXOS_INSTALL_REEXEC" ]; then
    export NIXOS_INSTALL_REEXEC=1
    exec unshare --mount --uts -- "$0" "$@"
  else
    mount --verbose --make-rprivate '/'
  fi
fi

# Parse the command line for the -I flag
extraBuildFlags=()
chrootCommand=('/run/current-system/sw/bin/bash')
buildUsersGroup='nixbld'

while [ "$#" -gt 0 ]; do
  i="$1"; shift 1
  case "$i" in
    '--max-jobs'|'-j'|'--cores'|'-I')
      j="$1"; shift 1
      extraBuildFlags+=("$i" "$j")
      ;;
    '--option')
      j="$1"; shift 1
      k="$1"; shift 1
      extraBuildFlags+=("$i" "$j" "$k")
      ;;
    '--root')
      MOUNT_POINT="$1"; shift 1
      ;;
    '--closure')
      closure="$1"; shift 1
      buildUsersGroup=""
      ;;
    '--no-channel-copy')
      noChannelCopy=1
      ;;
    '--no-root-passwd')
      noRootPasswd=1
      ;;
    '--no-bootloader')
      noBootLoader=1
      ;;
    '--show-trace')
      extraBuildFlags+=("$i")
      ;;
    '--chroot')
      runChroot=1
      if [ ! -z "$@" ]; then
        chrootCommand=("$@")
      fi
      break
      ;;
    '--help')
      exec man nixos-install
      exit 1
      ;;
    *)
      echo "$0: unknown option \`$i'" >&2
      exit 1
      ;;
  esac
done

set -e
shopt -s nullglob

declare -r MOUNT_POINT="${MOUNT_POINT:-/mnt}"

if ! test -e "$MOUNT_POINT"; then
  echo "mount point $MOUNT_POINT doesn't exist" >&2
  exit 1
fi

create_triton_fhs "${MOUNT_POINT}"

copy_host_file "${MOUNT_POINT}" '0644' 'etc/hosts'
copy_host_file "${MOUNT_POINT}" '0644' 'etc/resolv.conf'
copy_host_file "${MOUNT_POINT}" '0644' 'etc/ssl/certs/ca-certificates.crt' \
  'etc/ssl/certs/ca-bundle.crt'

rbind_host_file "${MOUNT_POINT}" 'etc/group'
rbind_host_file "${MOUNT_POINT}" 'etc/passwd'

rbind_host_dir "${MOUNT_POINT}" 'dev'
rbind_host_dir "${MOUNT_POINT}" 'proc'
rbind_host_dir "${MOUNT_POINT}" "tmp/root" '/'
rbind_host_dir "${MOUNT_POINT}" 'sys'

mount --verbose --types tmpfs --options 'mode=0755' none "$MOUNT_POINT/run"
mount --verbose --types tmpfs --options 'mode=0755' none \
  "$MOUNT_POINT/var/setuid-wrappers"
rm --verbose --recursive --force "$MOUNT_POINT/var/run"
ln --verbose --symbolic '/run' "$MOUNT_POINT/var/run"

if [ -n "$runChroot" ]; then
  if ! [ -L "$MOUNT_POINT/nix/var/nix/profiles/system" ]; then
    echo "$0: installation not finished; cannot chroot into installation directory" >&2
    exit 1
  fi
  ln --verbose --symbolic \
    '/nix/var/nix/profiles/system' "$MOUNT_POINT/run/current-system"
  exec chroot "$MOUNT_POINT" "${chrootCommand[@]}"
fi

# Get the path of the NixOS configuration file.
if test -z "$NIXOS_CONFIG"; then
  NIXOS_CONFIG='/etc/nixos/configuration.nix'
fi

if [ ! -e "$MOUNT_POINT/$NIXOS_CONFIG" ] && [ -z "$closure" ]; then
  echo "configuration file $MOUNT_POINT/$NIXOS_CONFIG doesn't exist" >&2
  exit 1
fi

chown @root_uid@:@nixbld_gid@ "$MOUNT_POINT/nix/store"

# There is no daemon in the chroot.
unset NIX_REMOTE

{'fraction_non_alphanumeric': 0.18819582125972242, 'fraction_numerical': 0.030044227543083727, 'mean_word_length': 2.8755910165484635, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3311', 'n_tokens_mistral': 5042, 'n_tokens_neox': 4706, 'n_words': 1134}