#!/bin/bash

# Must be root
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root."
  exit 1
fi

read -p "root password please: " CT_ROOT_PASS
read -p "CT Storage [default: tier1]: " CT_STORAGE
read -p "CT Hostname: " CT_HOSTNAME
read -p "CT NAME_SERVER [default: 192.168.10.4]: " CT_NAME_SERVER
read -p "CT ID [e.g. 44]: " CT_ID
#read -p "CT IP [e.g 44]: " CT_IP
read -p "CT Network ID [default: 10]: " CT_NET_ID
read -p "CT Bridge [default: vmbr0]: " CT_BRIDGE
read -p "CT Description: " CT_DESCRIPTION

CT_IP="$CT_ID"
CT_NET_ID=${CT_NET_ID:-10}

# Calculer le nombre de zéros nécessaires
len_CT_NET_ID=${#CT_NET_ID}    
len_CT_ID=${#CT_ID}    
total_length=5          # Longueur totale souhaitée
zeros_needed=$((total_length - len_CT_NET_ID - len_CT_ID))
# Générer les zéros nécessaires
if [ "$zeros_needed" -eq 0 ]; then
    zeros=""
else
    zeros=$(printf "%0${zeros_needed}d" 0)
fi

# Construire la variable finale
VM_ID="${CT_NET_ID}${zeros}${CT_ID}"

echo $VM_ID

#------ Variables ------#
CT_CORES=2
CT_MEMORY=4096
CT_SWAP=1024
CT_DISK_SIZE=8
CT_UNPRIVILEGED=1
# CT_NET_ID=${CT_NET_ID:-10}
CT_BRIDGE=${CT_BRIDGE:-vmbr0}
# CT_GW=${192.168.$CT_NET_ID.1}
CT_START=0
CT_STORAGE=${CT_STORAGE:-tier1}
CT_OS_TYPE=debian
CT_ON_BOOT=1
CT_SEARCH_DOMAIN=inxs.me
CT_NAME_SERVER=${CT_NAME_SERVER:-192.168.10.4}
CT_SSH_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG5Tjx2S5EKYANdrhZNucwuiI9by6FF3Lv0F7K+s2fM/ dbi@denis_mbp"
#------ Variables ------#

#------ LXC Creation ------#
pct create "$VM_ID" \
/mnt/pve/ket-software/template/cache/debian-12-standard_12.7-1_amd64.tar.zst \
--hostname "$CT_HOSTNAME" \
--description "$CT_DESCRIPTION" \
--cores "$CT_CORES" \
--memory "$CT_MEMORY" \
--swap "$CT_SWAP" \
--net0 name=eth0,bridge="$CT_BRIDGE",firewall=0,gw=192.168."$CT_NET_ID".1,ip=192.168."$CT_NET_ID"."$CT_IP"/24,type=veth \
--rootfs "$CT_DISK_SIZE" \
--storage "$CT_STORAGE" \
--unprivileged "$CT_UNPRIVILEGED" \
--ostype "$CT_OS_TYPE" \
--password="$CT_ROOT_PASS" \
--onboot "$CT_ON_BOOT" \
--nameserver "$CT_NAME_SERVER" \
--searchdomain "$CT_SEARCH_DOMAIN" \
--features fuse=1,keyctl=1,nesting=1 \
--mp5 /lxc_shares/scripts,mp=/opt/scripts_remote \
--mp6 /lxc_shares/backup,mp=/media/backup \
--start "$CT_START"
# --ssh-public-key "$CT_SSH_KEY" \
#------ LXC Creation ------#

#------ POST INSTALL ------#
echo "lxc.cgroup2.devices.allow: c 10:200 rwm" >> /etc/pve/lxc/$VM_ID.conf
echo "lxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file" >> /etc/pve/lxc/$VM_ID.conf
#------ POST INSTALL ------#