infra-generale/create.sh

105 lines
2.7 KiB
Bash
Raw Permalink Normal View History

2024-08-20 12:10:44 +02:00
#!/bin/bash
# Script to create a virtual machine
#
# Copyright (C) 2024 Adrien 'neox' Bourmault <neox@a-lec.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Exit on error
set -e
#set -v
# Enable quitting properly
trap clean_exit INT
function clean_exit() {
echo "Exiting..."
set +e
umount -q /mnt/${vm}
sync
if [ ! -z ${loopdisk} ]; then
losetup -d ${loopdisk}
fi
sleep 3
rmdir /mnt/${vm}*
exit 0
}
vm=$1
dest=$2
if [ -e ${dest} ]; then
echo -e "\e[1m\e[31mThis virtual machine already exists!\e[0m"
exit 1
fi
generic_image="/srv/vmverse/installation/generic-trisquel.a-lec.org.raw"
generic_xml="/srv/vmverse/installation/generic-trisquel.a-lec.org.xml"
if [[ $# < 2 ]]
then
echo "ERROR: 3 parameters required : vm domain, destination path"
exit 1
fi
# Preparing path
echo "Preparing path..."
mkdir -p /mnt/${vm}
mkdir -p $(dirname ${dest})
# Creating new disk
echo "Creating new disk..."
cp --reflink ${generic_image} ${dest}
# Mounting
echo "Mounting devices..."
loopdisk=$(losetup -fPL ${dest} --show)
mount ${loopdisk}p1 /mnt/${vm}
# Customizing
echo "Updating system files..."
rm -f /mnt/${vm}/var/lib/dhcp/*
sed -i "s/generic-trisquel.a-lec.org/${vm}/g" /mnt/${vm}/etc/postfix/virtual
sed -i "s/generic-trisquel.a-lec.org/${vm}/g" /mnt/${vm}/etc/mailname
sed -i "s/generic-trisquel.a-lec.org/${vm}/g" /mnt/${vm}/etc/postfix/main.cf
sed -i "s/generic-trisquel.a-lec.org/${vm}/g" /mnt/${vm}/etc/hosts
sed -i "s/generic-trisquel//g" /mnt/${vm}/etc/hosts
# Cleaning up
echo -e "Unmounting..."
umount -q /mnt/${vm}
sync
if [ ! -z ${loopdisk} ]; then
losetup -d ${loopdisk}
fi
sleep 3
rmdir /mnt/${vm}*
# Registering vm
echo "Registering vm..."
rm -f /tmp/${vm}.xml
cp ${generic_xml} /tmp/${vm}.xml
mac=`echo 52:54:00$(od -An -N3 -tx1 /dev/urandom | tr ' ' ':')`
uuid=`uuid`
sed -i "s;${generic_image};${dest};g" /tmp/${vm}.xml
sed -i "s/311541de-2383-49b1-a014-d4e558bdaad4/${uuid}/g" /tmp/${vm}.xml
sed -i "s/52:54:00:0b:a6:ed/${mac}/g" /tmp/${vm}.xml
sed -i "s/generic-trisquel.a-lec.org/${vm}/g" /tmp/${vm}.xml
virsh define /tmp/${vm}.xml
echo -e "\e[36m${vm} successfully created\e[0m"
echo Generated mac address: ${mac}
exit 0