aboutsummaryrefslogtreecommitdiffstats
path: root/mkbuild.sh
blob: 4820cb12149c8b609f07546d29520475aaeef405 (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
#!/usr/bin/env bash
#
# made by Dennis Eriksen <dnns.no> in 2019. Gitified in 2020.

# Exit on error. Append "|| true" if you expect an error.
set -o errexit
# Exit on error inside any functions or subshells.
set -o errtrace
# Do not allow use of undefined vars. Use ${VAR:-} to use an undefined VAR
set -o nounset
# Catch the error in case mysqldump fails (but gzip succeeds) in `mysqldump |gzip`
set -o pipefail

function die {
  echo $@
  exit 1
}

function main {

  # Check if $1 exists
  [[ "${1:-}" == "" ]] && die "You need to set the name of the machine you want to rebuild."
  local NAME=${1}

  # Check if mkosi-template exists, and cd into it if it does
  [[ -d /srv/mkosi/${NAME} ]] || die "/srv/mkosi/${NAME} does not exist"
  cd /srv/mkosi/"${NAME}"
  mkosi -o "/var/lib/machines/${NAME}.new"

  # Stop machine if it is running
  if machinectl status "${NAME}" >/dev/null; then
    machinectl stop "${NAME}"
  fi

  cd /var/lib/machines
  if [[ -e "${NAME}" ]]; then
    mv "${NAME}" .backup/
    rm -f "${NAME}.nspawn"
  fi
  mv "${NAME}.new" "${NAME}"
  mv "${NAME}.new.nspawn" "${NAME}.nspawn"
  echo "Done building."
  echo ""
  sleep 1
  echo "Starting"
  machinectl start "${NAME}"
  sleep 2
  machinectl


  if [[ -e ".backup/${NAME}" ]]; then
    echo ""
    echo "Now zipping up the old machine, for backup"
    cd .backup
    tar c "${NAME}" | xz -0 - > "/var/lib/machines/.backup/${NAME}.tar.xz.$(date +%Y%m%d%H%M%S)"
    rm -r "${NAME}"
    cd ..
  fi

}

main $@