#!/bin/bash
#/usr/bin/firststartAlt.sh -s {share_url} -n {Username} -p {Password}
#/usr/bin/firststartAlt.sh -s "//10.10.243.33/Profiles" -n {Username} -p {Password}
#v1_010624

while getopts "d:s:n:p:" option; do
    case $option in    
    s) share_url=$OPTARG ;;
    n) username=$OPTARG ;;
    p) password=$OPTARG ;;
    \?) # Invalid option
        echo "Error: Invalid option"
        exit 1
        ;;
    esac
done

#macadr=$(cat /sys/class/net/*/address|head -n1|sed 's/://g')
source_folder="Profiles/DATAON_"
destination_folder="/mnt/windowsfiles"
tempfolder="/mnt/wincopy"
hostname=$(hostname)
mkdir /mnt/samba
mkdir /mnt/samba/images
log_file="/tmp/backaping.log"
workdir="/mnt/samba/images"
compuuid=$(cat /sys/class/dmi/id/product_uuid)
name=$compuuid"_windows.qcow2"
nfsfolder="windows"
smbfolder="Profiles"
qcow2dirdst="/var/lib/libvirt/images"
mkdir -p -m 777 $tempfolder
mkdir $destination_folder


#install kvm software
apt update
apt install rename -y
apt install cifs-utils -y
apt install qemu-utils -y
apt install astra-kvm -y
# Подключение к сетевому хранилищу
mount.cifs "$share_url" "$workdir" -o username="$username",password="$password",nobrl

#qemu-img convert $workdir/$name -O qcow2 -c $qcow2dirdst/windows.qcow2
cp $workdir/$name $qcow2dirdst/windows.qcow2
usermod -a -G libvirt-admin colibri
usermod -a -G kvm,libvirt,libvirt-qemu,libvirt-admin root
usermod -a -G kvm,libvirt,libvirt-qemu,libvirt-admin colibri
uui=$(uuidgen)
mac="52:54:00:$((RANDOM % 10))$((RANDOM % 10)):$((RANDOM % 10))$((RANDOM % 10)):$((RANDOM % 10))$((RANDOM % 10))"
#create network config
cat <<EOL >/etc/libvirt/qemu/networks/default.xml
        <network>
          <name>default</name>
          <uuid>$uui</uuid>
          <forward mode='nat'/>
          <bridge name='virbr0' stp='on' delay='0'/>
          <mac address='$mac'/>
          <ip address='192.168.122.1' netmask='255.255.255.0'>
            <dhcp>
              <range start='192.168.122.2' end='192.168.122.254'/>
            </dhcp>
          </ip>
        </network>
EOL
#create and start
virsh net-define /etc/libvirt/qemu/networks/default.xml
virsh net-start default
#autostart
ln -s /etc/libvirt/qemu/networks/default.xml /etc/libvirt/qemu/networks/autostart/default.xml

#Create machine
vm_name='windows'
#virsh undefine --nvram $vm_name
#virsh domid $vm_name
let "memory=$(free -m | grep -oP '\d+' | head -n 1)/2"
let "vcpu=$(nproc --all)/2"
disk_file_path=/var/lib/libvirt/images/windows.qcow2

vm_file_path=/etc/libvirt/qemu/windows.xml

if [ -d /sys/firmware/efi ]; then
	loader='<loader readonly='\''yes'\'' type='\''pflash'\''>/usr/share/OVMF/OVMF_CODE.fd</loader>'
	#nvram='<nvram>/var/lib/libvirt/qemu/nvram/$vm_name_VARS.fd</nvram>'
fi

cat <<EOL >/etc/libvirt/qemu/windows.xml
        <domain type='qemu'>
          <name>windows</name>
          <memory unit='MiB'>${memory}</memory>
          <vcpu placement='static'>${vcpu}</vcpu>
          <os>
            <type arch='x86_64' machine='pc-q35-5.0'>hvm</type>
             ${loader} 
          </os>
          <features>
            <acpi/>
            <apic/>
            <hyperv>
              <relaxed state='on'/>
              <vapic state='on'/>
              <spinlocks state='on' retries='8191'/>
            </hyperv>
          </features>         
          <clock offset='localtime'/>
          <on_poweroff>destroy</on_poweroff>
          <on_reboot>restart</on_reboot>
          <on_crash>destroy</on_crash>
          <pm>
            <suspend-to-mem enabled='no'/>
            <suspend-to-disk enabled='no'/>
          </pm>
          <devices>
            <emulator>/usr/bin/qemu-system-x86_64</emulator>
            <disk type='file' device='disk'>
              <driver name='qemu' type='qcow2'/>
              <source file='${disk_file_path}'/>
              <target dev='sda' bus='sata'/>
              <boot order='1'/>
            </disk>
            <interface type='network'>
              <source network='default'/>
              <model type='e1000'/>
            </interface>
            <controller type='virtio-serial' index='0'/>
            <channel type='spicevmc'>
              <target type='virtio' name='com.redhat.spice.0'/>
            </channel>
            <channel type='unix'>
              <target type='virtio' name='org.qemu.guest_agent.0'/>
            </channel>
            <graphics type='spice' port='5902' autoport='no' keymap='en-us'>
              <gl enable='no'/>
            </graphics>
            <video>
              <model type='qxl'/>
            </video>
            <sound model='ich9'/>
            <input type='tablet'/>
            <controller type='usb' index='0' model='ich9-ehci1'/>
            <controller type='usb' index='0' model='ich9-uhci1'>
              <master startport='0'/>
            </controller>
            <controller type='usb' index='0' model='ich9-uhci2'>
              <master startport='2'/>
            </controller>
            <controller type='usb' index='0' model='ich9-uhci3'>
              <master startport='4'/>
            </controller>
            <redirdev bus='usb' type='spicevmc'/>
            <redirdev bus='usb' type='spicevmc'/>
            <redirdev bus='usb' type='spicevmc'/>
            <redirdev bus='usb' type='spicevmc'/>
          </devices>
        </domain>
EOL

virsh define $vm_file_path

#virsh list --all

# Отключение сетевого хранилища
umount "$tempfolder"
umount "$workdir"

#############################################################################################################################
#create service for each user loggin
cat <<EOL >/usr/local/bin/changeuserconf.sh
#!/bin/bash
user=\$(echo \$USER | cut -d'@' -f1 | tr A-Z a-z)
find /mnt/windowsfiles/wincopy/ -maxdepth 1 -type d | xargs -n 1 rename -v 's/(.*)\/([^\/]*)/\$1\/\L\$2/' {}
source_folder="/mnt/windowsfiles/wincopy/\$user/"

desktop_folder=\$(systemd-path user-desktop)

cat <<EOL >"\$desktop_folder/virt-manager.desktop"
[Desktop Entry]
Name[ru]=Виртуальная Windows машина
Type=Application
NoDisplay=false
Exec=sudo virt-manager
Icon=virt-manager
Hidden=false
Terminal=false
StartupNotify=false
#EOL
EOL
sed -i 's/#EOL/EOL/g' /usr/local/bin/changeuserconf.sh

chmod 774 /usr/local/bin/changeuserconf.sh
chmod +x /usr/local/bin/changeuserconf.sh
cat <<EOL >/etc/systemd/user/changeuserconf.service
[Unit]
Description=This service changes user conf files for apps like  Pidgin

[Service]
Type=simple
#Type=oneshot
ExecStart=/bin/bash -c "/usr/local/bin/changeuserconf.sh"
Restart=on-failure
RestartSec=20s

[Install]
WantedBy=default.target
EOL
# start service
systemctl --global enable changeuserconf.service || true
