#!/bin/bash

[[ -v installbase ]] || source /var/tmp/install/common.sh

firstboot() {
  local segment file storage software rc=0
  echo 1 > /proc/sys/kernel/printk
  storage=$(get_profile .storage)
  software=$(get_profile .software)
  [[ $storage ]] || return
  [[ $software ]] || return
  for segment in storage/$storage software/$software; do
    file=$installbase/$segment/firstboot
    if [[ -f $file ]]; then
      1>&2 echo "Running: $file"
      $file || {
        rc=$?
        1>&2 echo "ERROR: $file"
      }
    fi
  done
  run set_timezone || return
  systemctl enable anyboot.service || return
  run set_target_anyboot || return
  if [[ -f /tmp/stop ]]; then
    1>&2 echo "Halted."
    sleep inf
  fi
  return "$rc"
}

return 2> /dev/null || {
  export NO_COLOR=1
  set -o pipefail
  mkdir -p /var/log/pflaster
  echo Running: $0
  firstboot 2>&1 | tee /var/log/pflaster/firstboot.txt || {
    echo "Halted after error."
    sleep inf
  }
  reboot
}
