#!/bin/bash
if [[ $# -lt 3 ]];then
    echo -e "\033[32m Usage: ./vm_recreate.sh IP/nm OS DISK uuid\033[0m"
    exit 1
fi

logger(){
    echo [$1] $2
    echo `date +"%Y-%m-%d %H:%M:%S "` [$1] $2 >> /tmp/$hostname.log
    if [[ ($1 != 'debug') && ( -n $u_uuid ) ]];then
        curl http://vm-mgr.service.ucloud.cn/vm-mgr/v1/vm/receive -X POST -H 'Content-Type:application/json' -d "{\"Action\":\"recreate\",\"UID\":\"$u_uuid\",\"SubStatus\":\"$1\",\"Info\":\"$2\"}"
    fi
    if [[ $1 = 'success' ]];then
        exit 0
    elif [[ $1 = 'failed' ]];then
        exit 1
    fi
} 

# get all conf
u_uuid=$4
dsize=$3

ipcalc -c $1
if [[ $? -ne 0 ]]; then
    logger "failed" "Validate IP address $1 failed"
fi
hostname='vm_recreate'

ipaddr=`echo $1|cut -f1 -d'/'`
hostname=`echo $ipaddr|tr . -`
nm=`echo $1|cut -f2 -d'/'`
netmask=`ipcalc -m $ipaddr/$nm|awk -F '=' '{print $2}'`
ga1=`ipcalc -n $ipaddr/$nm|awk -F '=' '{print $2}'|awk -F '.' '{print $1"."$2"."$3}'`
ga2=`ipcalc -n $ipaddr/$nm|awk -F '=' '{print $2}'|awk -F '.' '{print $4}'`
if [[ -z $ga1 || -z $ga2 ]];then
    logger "failed" "Validate IP address $1 failed"
fi
ga3=$(($ga2 + 1))
gateway="$ga1.$ga3"

if [[ -z $u_uuid ]];then
    u_uuid=`virsh domuuid $hostname`
fi

os=$2
case $os in
   CentOS6.3) img='CentOS6.3.img' ;;
   CentOS7.4-kernel-4.1.0) img='CentOS7.4.img-4.1.0-30-1'  ;;
   CentOS7.4) img='CentOS7.4.img'  ;;
   Windows2012) img='Windows2012.img' ;;
   Windows2016) img='windows-2016-zh-20190118-b5850041228840d360710e2b25df1473.qcow2' ;;
   Windows2019) img='Windows2019.img' ;;
   Windows2022) img='windows-2022.zh-20221108-d61d6444417ba8e72d75052c550e0d55.qcow2' ;;
   *)
       echo "not support os $os!"
       exit 1 ;;
esac

# check ip
ping -n -c 1 -w 5 $ipaddr
if [[ $? -eq 0 ]]; then
    logger "failed" "ip is used"
fi

# check vm is down
if [[ ! `virsh domstate $hostname` =~ 'shut off' ]]; then
    logger "failed" "vm is not shut off"
fi

# get conf by local env
test -g /dev/mapper/vg-data
IS_LVM=$?

lscpu >/dev/null
if [[ $? -ne 0 ]]; then
    logger "failed" "lscpu can not run"
fi

lscpu|grep "Model name"|grep "AMD"
IS_AMD=$?

lscpu|grep "Model name"|grep "Intel"|grep "6126\|6146"
IS_Skylake=$?

#check /opt/data
mount |grep -q '/opt/data'
if [[ $? -ne 0 ]];then
    logger "failed" "'/opt/data/' not in mount!"
fi

#create the img dir
dirname=$hostname'img'
if [ ! -d "/opt/data/$dirname" ]; then
    logger "failed" "this host is not existed"
fi

copy_create_img() {
logger "debug" "copy the img file"

bash <(curl -s http://softlib.service.ucloud.cn/usa/vmzone/Templateimg/checkfile.sh) /opt/data/Templateimg/${img}

if [[ $? -ne 0 ]];then
    logger "failed" "check img failed!"
fi

cp /opt/data/Templateimg/${img} /opt/data/$dirname/$hostname.img
if [[ $? -eq 0 ]];then
    logger "debug" "copy img done!"
else
    logger "failed" "copy img failed!"
fi

if [[ $dsize -gt 0 ]];then
    mv /opt/data/$dirname/$hostname.disk /opt/data/$dirname/$hostname.disk.delete-`date +%F-%H%M`
    qemu-img create -f qcow2 -o preallocation=metadata /opt/data/$dirname/$hostname.disk ${dsize}G
    disk_result=$?
fi

}

guestmount_modify_conf() {
    logger "debug" "guestmount to config"

    mountdir="/opt/op/$hostname"
    mkdir -p /opt/op/$hostname
    #mount img and modify hostname,ipaddr
    logger "debug" "start guestmount"
#    modprobe nbd
#    for i in {0..15}
#    do
#        nbd_dev="/dev/nbd$i"
#        if [[ -b $nbd_dev ]];then
#            lsof $nbd_dev
#            if [[ $? -ne 0 ]];then
#                break
#            fi
#        fi
#        nbd_dev=''
#    done
#    if [[ -n $nbd_dev ]];then
#        qemu-nbd -c $nbd_dev /opt/data/$dirname/$hostname.img
#    else
#        logger "debug" "nbd device not find"
#    fi
#    sleep 10
#    if [[ -b ${nbd_dev}p2 ]];then
#        mount ${nbd_dev}p2 $mountdir
#        mount_result=$?
#    else
#        mount ${nbd_dev}p1 $mountdir
#        mount_result=$?
#    fi
    mount_result=1
    if [[ $mount_result -ne 0 ]]; then
#        qemu-nbd -d $nbd_dev
#        logger "debug" "$nbd_dev mount failed"
        guestmount -a /opt/data/$dirname/$hostname.img -i $mountdir
        if [[ $? -ne 0 ]];then
            logger "failed" "guestmount failed"
        fi
    fi
    tmpHost="$mountdir/etc/sysconfig/network" 
    tmpIp="$mountdir/etc/sysconfig/network-scripts/ifcfg-eth0"

    if [[ $os = "Windows2016" || $os = "Windows2019" ]];then
        tmpBat="$mountdir/bootstrap.bat"

        cat > $tmpBat <<EOF
netsh interface ip set address name="以太网 3" source=static address=$ipaddr mask=$netmask gateway=$gateway
netsh interface ip set dns name="以太网 3" source=static address="$dns1"
netsh interface ip add dns name="以太网 3" address="$dns2"

netsh advfirewall set allprofiles state off

net user Administrator ucloud12#$

del %0 | move *.* d:\

EOF
        iconv -f utf8 -t gbk -o ${tmpBat}.tmp $tmpBat
        mv ${tmpBat}.tmp $tmpBat
        unix2dos $tmpBat

    elif [[ $os = 'Windows2022' ]];then
        tmpBat="$mountdir/bootstrap.bat"

        cat > $tmpBat <<EOF
netsh interface ip set address name="以太网 2" source=static address=$ipaddr mask=$netmask gateway=$gateway
netsh interface ip set dns name="以太网 2" source=static address="$dns1"
netsh interface ip add dns name="以太网 2" address="$dns2"

netsh advfirewall set allprofiles state off

net user Administrator ucloud12#$

del %0 | move *.* d:\

EOF
        iconv -f utf8 -t gbk -o ${tmpBat}.tmp $tmpBat
        mv ${tmpBat}.tmp $tmpBat
        unix2dos $tmpBat

    elif [[ $os = "Windows2012" ]];then
        tmpBat="$mountdir/Windows/setip.bat"

        cat > $tmpBat <<EOF
@echo off
cmd /c netsh interface ip set address name="eth0" source=static addr=$ipaddr mask=$netmask gateway=$gateway
cmd /c netsh interface ip set dns name="eth0" source=static addr="$dns1"
cmd /c netsh interface ip add dns name="eth0" addr="$dns2"

ipconfig /all

net user Administrator ucloud12#$

del %0 | move *.* d:\

EOF

    elif [[ $os =~ "CentOS" ]];then
        if [ $os = "CentOS6.3" ];then
            sed -i "s/HOSTNAME=.*/HOSTNAME=$hostname/g" $tmpHost
        else
            echo "$hostname" > $mountdir/etc/hostname
        fi

        cat > $tmpIp <<EOF
DEVICE="eth0"
BOOTPROTO="static"
TYPE="Ethernet"
ONBOOT="yes"
IPADDR=$ipaddr
NETMASK=$netmask
GATEWAY=$gateway
EOF

############ ipv6 set ##############

ifcfgv6=$mountdir'/etc/sysconfig/network-scripts/ifcfg-sit6to4'
routev6=$mountdir'/etc/sysconfig/network-scripts/route6-sit6to4'
SYSCTL=$mountdir'/etc/sysctl.conf'

IPV4=$ipaddr

IPV6=2002:`echo "${IPV4}" |awk -F '.' '{printf "%02x%02x:%02x%02x\n",$1,$2,$3,$4}'`::1

sed -i --follow-symlinks "/net\.ipv6\.conf\.all\.disable_ipv6.*/d" $SYSCTL

cat > $ifcfgv6 <<EOF
DEVICE=sit6to4
TYPE=sit
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=static
IPV6INIT=yes
IPV6TUNNELIPV4=any
IPV6TUNNELIPV4LOCAL=$IPV4
IPV6ADDR=$IPV6/128
EOF

cat > $routev6 <<EOF
2002:c0a8::/32 dev sit6to4 src $IPV6 metric 8
2002:ac10::/28 dev sit6to4 src $IPV6 metric 8
2002:a00::/24 dev sit6to4 src $IPV6 metric 8
2002:6460::/27 dev sit6to4 src $IPV6 metric 8
EOF


        #add key
        mkdir $mountdir/root/.ssh 2>/dev/null
        #echo "ssh-rsa [payload removed: 372 characters] root@UCloud-Servers" >> $mountdir/root/.ssh/authorized_keys
     echo "ssh-rsa [payload removed: 544 characters] isl_sod@ucloud.cn_UcloudServers-v2-2022-10-17" > $mountdir/root/.ssh/authorized_keys
     echo "ssh-rsa [payload removed: 372 characters] root@10-81-96-153"  >> $mountdir/root/.ssh/authorized_keys
        # auto mount vdb

        cat > $mountdir/tmp/add_disk.sh <<EOF
#!/bin/bash

vdb_exist=\`lsblk|grep -i vdb\`
vdb_ext4_exist=\`blkid|grep -i vdb\`

if [ -n "\$vdb_exist" ];then
    if [ -z "\$vdb_ext4_exist" ];then
        mkfs -t ext4 /dev/vdb
    fi
    mkdir /data
    mount -t ext4 /dev/vdb /data/
    if [[ $? -eq 0 ]];then
        echo '/dev/vdb                /data                   ext4    defaults,noatime  0 0' >> /etc/fstab
    fi
fi
sed -i.bak -c '/add_disk.sh/d' /etc/rc.d/rc.local
EOF

        echo '/bin/bash -x /tmp/add_disk.sh' >> $mountdir/etc/rc.d/rc.local
        chmod +x $mountdir/etc/rc.d/rc.local

        #复制宿主的dns配置
        cp -f /etc/resolv.conf $mountdir/etc/resolv.conf

        ## 清理模板中的历史操作
        echo ''> $mountdir/etc/udev/rules.d/70-persistent-net.rules
        echo ''> $mountdir/root/.bash_history
        echo ''> $mountdir/var/log/wtmp
        echo ''> $mountdir/var/log/btmp
        sed -i "/vdb/d" $mountdir/etc/fstab

    fi

    sync
    umount $mountdir
    sleep 10

    if [[ -n $nbd_dev ]];then
        qemu-nbd -d $nbd_dev
        if [ $? -ne 0 ];then
            logger "failed" "failed to disconnect $nbd_dev"
        fi
    fi

    rmdir $mountdir

    if [ $? -ne 0 ];then
        logger "failed" "failed to clean up mount point"
    fi
}
start_vm() {
    virsh start $hostname
    if [ $? -ne 0 ];then 
        logger "failed" "start vm failed"
    fi
    logger "success" "create_success"
}

copy_create_img
guestmount_modify_conf
start_vm
