haos-vm.sh 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #!/usr/bin/env bash
  2. YW=`echo "\033[33m"`
  3. BL=`echo "\033[36m"`
  4. GN=`echo "\033[1;92m"`
  5. CL=`echo "\033[m"`
  6. BFR="\\r\\033[K"
  7. HOLD="-"
  8. CM="${GN}✓${CL}"
  9. while true; do
  10. read -p "This will create a New Home Assistant OS VM. Proceed(y/n)?" yn
  11. case $yn in
  12. [Yy]* ) break;;
  13. [Nn]* ) exit;;
  14. * ) echo "Please answer yes or no.";;
  15. esac
  16. done
  17. clear
  18. function header_info {
  19. echo -e "${BL}
  20. _ _ ____ _____
  21. | | | | /\ / __ \ / ____|
  22. | |__| | / \ | | | | (___
  23. | __ | / /\ \| | | |\___ \
  24. | | | |/ ____ \ |__| |____) |
  25. |_| |_/_/ \_\____/|_____/
  26. ${CL}"
  27. }
  28. header_info
  29. function msg_info() {
  30. local msg="$1"
  31. echo -ne " ${HOLD} ${YW}${msg}..."
  32. }
  33. function msg_ok() {
  34. local msg="$1"
  35. echo -e "${BFR} ${CM} ${GN}${msg}${CL}"
  36. }
  37. set -o errexit
  38. set -o errtrace
  39. set -o nounset
  40. set -o pipefail
  41. shopt -s expand_aliases
  42. alias die='EXIT=$? LINE=$LINENO error_exit'
  43. trap die ERR
  44. trap cleanup EXIT
  45. function error_exit() {
  46. trap - ERR
  47. local DEFAULT='Unknown failure occured.'
  48. local REASON="\e[97m${1:-$DEFAULT}\e[39m"
  49. local FLAG="\e[91m[ERROR] \e[93m$EXIT@$LINE"
  50. msg "$FLAG $REASON"
  51. [ ! -z ${VMID-} ] && cleanup_vmid
  52. exit $EXIT
  53. }
  54. function warn() {
  55. local REASON="\e[97m$1\e[39m"
  56. local FLAG="\e[93m[WARNING]\e[39m"
  57. msg "$FLAG $REASON"
  58. }
  59. function info() {
  60. local REASON="$1"
  61. local FLAG="\e[36m[INFO]\e[39m"
  62. msg "$FLAG $REASON"
  63. }
  64. function msg() {
  65. local TEXT="$1"
  66. echo -e "$TEXT"
  67. }
  68. function cleanup_vmid() {
  69. if $(qm status $VMID &>/dev/null); then
  70. if [ "$(qm status $VMID | awk '{print $2}')" == "running" ]; then
  71. qm stop $VMID
  72. fi
  73. qm destroy $VMID
  74. fi
  75. }
  76. function cleanup() {
  77. popd >/dev/null
  78. rm -rf $TEMP_DIR
  79. }
  80. TEMP_DIR=$(mktemp -d)
  81. pushd $TEMP_DIR >/dev/null
  82. while read -r line; do
  83. TAG=$(echo $line | awk '{print $1}')
  84. TYPE=$(echo $line | awk '{printf "%-10s", $2}')
  85. FREE=$(echo $line | numfmt --field 4-6 --from-unit=K --to=iec --format %.2f | awk '{printf( "%9sB", $6)}')
  86. ITEM=" Type: $TYPE Free: $FREE "
  87. OFFSET=2
  88. if [[ $((${#ITEM} + $OFFSET)) -gt ${MSG_MAX_LENGTH:-} ]]; then
  89. MSG_MAX_LENGTH=$((${#ITEM} + $OFFSET))
  90. fi
  91. STORAGE_MENU+=( "$TAG" "$ITEM" "OFF" )
  92. done < <(pvesm status -content images | awk 'NR>1')
  93. if [ $((${#STORAGE_MENU[@]}/3)) -eq 0 ]; then
  94. warn "'Disk image' needs to be selected for at least one storage location."
  95. die "Unable to detect valid storage location."
  96. elif [ $((${#STORAGE_MENU[@]}/3)) -eq 1 ]; then
  97. STORAGE=${STORAGE_MENU[0]}
  98. else
  99. while [ -z "${STORAGE:+x}" ]; do
  100. STORAGE=$(whiptail --title "Storage Pools" --radiolist \
  101. "Which storage pool you would like to use for the container?\n\n" \
  102. 16 $(($MSG_MAX_LENGTH + 23)) 6 \
  103. "${STORAGE_MENU[@]}" 3>&1 1>&2 2>&3) || exit
  104. done
  105. fi
  106. msg_ok "Using ${CL}${BL}$STORAGE${CL} ${GN}for Storage Location."
  107. VMID=$(pvesh get /cluster/nextid)
  108. msg_ok "Container ID is ${CL}${BL}$VMID${CL}."
  109. msg_info "Getting URL for Latest Home Assistant Disk Image"
  110. RELEASE_TYPE=qcow2
  111. URL=$(cat<<EOF | python3
  112. import requests
  113. url = "https://api.github.com/repos/home-assistant/operating-system/releases"
  114. r = requests.get(url).json()
  115. if "message" in r:
  116. exit()
  117. for release in r:
  118. if release["prerelease"]:
  119. continue
  120. for asset in release["assets"]:
  121. if asset["name"].find("$RELEASE_TYPE") != -1:
  122. image_url = asset["browser_download_url"]
  123. print(image_url)
  124. exit()
  125. EOF
  126. )
  127. if [ -z "$URL" ]; then
  128. die "Github has returned an error. A rate limit may have been applied to your connection."
  129. fi
  130. msg_ok "Found URL for Latest Home Assistant Disk Image"
  131. msg_ok "${CL}${BL}${URL}${CL}"
  132. wget -q --show-progress $URL
  133. echo -en "\e[1A\e[0K"
  134. FILE=$(basename $URL)
  135. msg_ok "Downloaded ${RELEASE_TYPE} Disk Image"
  136. msg_info "Extracting Disk Image"
  137. case $FILE in
  138. *"gz") gunzip -f $FILE ;;
  139. *"zip") gunzip -f -S .zip $FILE ;;
  140. *"xz") xz -d $FILE ;;
  141. *) die "Unable to handle file extension '${FILE##*.}'.";;
  142. esac
  143. STORAGE_TYPE=$(pvesm status -storage $STORAGE | awk 'NR>1 {print $2}')
  144. case $STORAGE_TYPE in
  145. btrfs|nfs|dir)
  146. DISK_EXT=".qcow2"
  147. DISK_REF="$VMID/"
  148. IMPORT_OPT="-format qcow2"
  149. esac
  150. for i in {0,1}; do
  151. disk="DISK$i"
  152. eval DISK${i}=vm-${VMID}-disk-${i}${DISK_EXT:-}
  153. eval DISK${i}_REF=${STORAGE}:${DISK_REF:-}${!disk}
  154. done
  155. msg_ok "Extracted Disk Image"
  156. msg_info "Creating HAOS VM"
  157. VM_NAME=$(sed -e "s/\_//g" -e "s/.${RELEASE_TYPE}.*$//" <<< $FILE)
  158. qm create $VMID -agent 1 -bios ovmf -cores 2 -memory 4096 -name $VM_NAME -net0 virtio,bridge=vmbr0 \
  159. -onboot 1 -ostype l26 -scsihw virtio-scsi-pci
  160. pvesm alloc $STORAGE $VMID $DISK0 128 1>&/dev/null
  161. qm importdisk $VMID ${FILE%.*} $STORAGE ${IMPORT_OPT:-} 1>&/dev/null
  162. qm set $VMID \
  163. -efidisk0 ${DISK0_REF},size=128K \
  164. -scsi0 ${DISK1_REF},size=32G >/dev/null
  165. qm set $VMID \
  166. -boot order=scsi0 >/dev/null
  167. set +o errtrace
  168. (
  169. msg_ok "Created HAOS VM ${CL}${BL}${VM_NAME}"
  170. msg_info "Adding Serial Port and Configuring Console"
  171. trap '
  172. warn "Unable to configure serial port. VM is still functional."
  173. if [ "$(qm config $VMID | sed -n ''/serial0/p'')" != "" ]; then
  174. qm set $VMID --delete serial0 >/dev/null
  175. fi
  176. exit
  177. ' ERR
  178. msg_ok "Added Serial Port and Configured Console"
  179. if [ "$(command -v kpartx)" = "" ]; then
  180. msg_info "Installing kpartx"
  181. apt-get update >/dev/null
  182. apt-get -qqy install kpartx &>/dev/null
  183. msg_ok "Installed kpartx"
  184. fi
  185. DISK1_PATH="$(pvesm path $DISK1_REF)"
  186. DISK1_PART1="$(kpartx -al $DISK1_PATH | awk 'NR==1 {print $1}')"
  187. DISK1_PART1_PATH="/dev/mapper/$DISK1_PART1"
  188. TEMP_MOUNT="${TEMP_DIR}/mnt"
  189. trap '
  190. findmnt $TEMP_MOUNT >/dev/null && umount $TEMP_MOUNT
  191. command -v kpartx >/dev/null && kpartx -d $DISK1_PATH
  192. ' EXIT
  193. kpartx -a $DISK1_PATH
  194. mkdir $TEMP_MOUNT
  195. mount $DISK1_PART1_PATH $TEMP_MOUNT
  196. sed -i 's/$/ console=ttyS0/' ${TEMP_MOUNT}/cmdline.txt
  197. qm set $VMID -serial0 socket >/dev/null
  198. )
  199. msg_info "Starting Home Assistant OS VM"
  200. qm start $VMID
  201. msg_ok "Started Home Assistant OS VM"
  202. msg_ok "Completed Successfully!\n"