#!/bin/bash

if [ -f /etc/os-release ]; then
    source /etc/os-release
fi

if [ "$ID" = "tencentos" -a "$VERSION" = "3.1 (Final)" ]; then
  ID="centos"
  VERSION="8"
  VERSION_ID="8"
fi

if [ "$ID" = "fusionos" -a "$VERSION" = "22" ]; then
  ID="centos"
  VERSION="8"
  VERSION_ID="8"
fi

# Debian 13 must use the dedicated updater. The legacy logic below contains
# RHEL/CentOS-only rpm/yum and network-scripts operations.
case "${ID}:${VERSION_ID:-${VERSION%% *}}" in
  debian:13|debian:13.*)
    update_script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
    for debian13_updater in \
      "$update_script_dir/cloud/apps/update_debian13" \
      /usr/local/zjmf/cloud/apps/update_debian13
    do
      if [ -f "$debian13_updater" ]; then
        exec /bin/bash "$debian13_updater" "$@"
      fi
    done
    echo '[debian13-update] dedicated updater is missing' >&2
    exit 1
    ;;
esac

# flush bin parmay
chmod +x /usr/local/zjmf/bin/*
if [ -f /usr/local/zjmf/cloud/network/set_kvm_rate_limit ]; then
  chmod 755 /usr/local/zjmf/cloud/network/set_kvm_rate_limit
fi

http_server='http://{mirror1.cloud.idcsmart.com,mirror2.cloud.idcsmart.com,mirror.cloud.idcsmart.com}/cloud/compute'

if [ `grep oneMinute.php /var/spool/cron/root |wc -l` -eq 0 ];then
	sed -i 's/cloudGetChart/oneMinute/g' /var/spool/cron/root
fi

conf_header=$(cat /usr/local/zjmf/conf/zjmf.conf|head -n1)
if [ "$conf_header" != "[default]" ];then
   sed -i '1 i\[default]' /usr/local/zjmf/conf/zjmf.conf
fi

if [ `rpm -qa |grep libguestfs-winsupport |wc -l` -eq 0 -o `rpm -qa |grep ntfs-3g |wc -l` -eq 0 ];then
	aria2c -x 5 -k 1M -c http://mirror.cloud.idcsmart.com/cloud/compute/202_packages.tar.gz -d /tmp
	cd /tmp
	tar xf 202_packages.tar.gz
	cd 202_packages
	for package in `ls *.rpm`;do
		rpm -ivh $package --nodeps > /dev/null 2>&1
	done
	rm -rf /tmp/202_packages*
fi

if [ ! -f "/etc/modprobe.d/nbd.conf" ];then
aria2c -x 5 -k 1M -c http://mirror.cloud.idcsmart.com/cloud/compute/nbd.ko.xz -d /tmp
\mv /tmp/nbd.ko.xz /lib/modules/$(uname -r)/kernel/drivers/block/
cat > /etc/modprobe.d/nbd.conf << EOF
options nbd max_part=8
EOF
depmod -a
modprobe nbd
fi

# version 2.0.9
if [ `ovs-vsctl list Bridge |grep name |grep ovs-tun |wc -l` -eq 0 ];then
	ovs-vsctl add-br ovs-tun
	ovs-vsctl set Bridge ovs-tun other_config=disable-in-band=true,datapath-id=0000fe9f17664a43
	ovs-vsctl set-controller ovs-tun tcp:127.0.0.1:6653
	ovs-vsctl add-port ovs-ext oext-to-otun -- set interface oext-to-otun type=patch options:peer=otun-to-oext
	ovs-vsctl add-port ovs-tun otun-to-oext -- set interface otun-to-oext type=patch options:peer=oext-to-otun
fi

# version 2.1.0
#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ `grep Before /usr/lib/systemd/system/supervisord.service |wc -l` -eq 0 ];then
#    sed -i '/After/iBefore=rc-local.service' /usr/lib/systemd/system/supervisord.service
#    sed -i 's/rc-local.service nss-user-lookup.target/nss-user-lookup.target/g' /usr/lib/systemd/system/supervisord.service
#    systemctl daemon-reload
#  fi
#fi

if [ ! -f "/etc/sysconfig/network-scripts/ifcfg-ovs-tun" ];then
cat > /etc/sysconfig/network-scripts/ifcfg-ovs-tun << EOF
DEVICE=ovs-tun
ONBOOT=yes
DEVICETYPE=ovs
TYPE=OVSIntPort
EOF
ifup ovs-tun >/dev/null 2>&1
fi

# version 2.1.2
#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ `grep "/etc/supervisord.d.*ini" /etc/supervisord.conf |wc -l` -eq 0 ];then
#cat > /etc/supervisord.conf << 'EOF'
#[unix_http_server]
#file=/var/run/supervisor/supervisor.sock
#chmod=0777
#[supervisord]
#logfile=/var/log/supervisor/supervisord.log
#logfile_maxbytes=50MB
#logfile_backups=10
#loglevel=info
#pidfile=/var/run/supervisord.pid
#nodaemon=false
#minfds=1024
#minprocs=200
#[rpcinterface:supervisor]
#supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
#[supervisorctl]
#serverurl=unix:///var/run/supervisor/supervisor.sock
#[include]
#files = /etc/supervisord.d/*.ini
#EOF
#
#    if [ ! -f "/etc/supervisord.d/aria2.ini" ];then
#cat > /etc/supervisord.d/aria2.ini << 'EOF'
#[program:aria2]
#command = /usr/local/zjmf/bin/aria2c --conf-path=/usr/local/zjmf/conf/aria2.conf
#directory = /usr/local/zjmf/bin/
#priority = 1
#numprocs = 1
#autostart = true
#autorestart = true
#startretries = 10
#stopwaitsecs = 1
#stopasgroup = true
#killasgroup = true
#stopsignal = KILL
#redirect_stderr = true
#EOF
#
#    fi
#
#    if [ -d "/usr/local/zjmf/conf/supervisord.d" ];then
#      \cp /usr/local/zjmf/conf/supervisord.d/*.ini /etc/supervisord.d
#    fi
#    supervisorctl update
#  fi
#fi

if [ ! -f "/usr/local/zjmf/conf/aria2.conf" ];then
cat > /usr/local/zjmf/conf/aria2.conf << 'EOF'
# aria2 config
continue=true
file-allocation=trunc
parameterized-uri=true
max-connection-per-server=3
max-concurrent-downloads=5
max-overall-download-limit=0
max-download-limit=0
disable-ipv6=true
min-split-size=1M
enable-rpc=true
rpc-listen-port=6800
dir=/home/kvm/images
EOF
fi

#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ `supervisorctl status |grep ryu-manager |wc -l` -ne 0 ];then
#    systemctl start supervisord
#  fi
#fi

# version 2.1.3
if [ `ovs-ofctl dump-flows ovs-tun |grep "00:00:00:00:00:00/01:00:00:00:00:00" |wc -l` -eq 0 ];then
  ovs-vsctl set-controller ovs-tun
  ovs-vsctl set-controller ovs-tun tcp:127.0.0.1:6653
fi

[ -f "/usr/local/zjmf/cloud/api/api.so" ] && rm -rf /usr/local/zjmf/cloud/api/api.so

# version 2.1.7
#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ ! -f /usr/lib/systemd/system/flowentryd.service ];then
#cat > /usr/lib/systemd/system/flowentryd.service <<EOF
#[Unit]
#Description=OpenFlow Entries Daemon
#After=openvswitch.service supervisord.service
#
#[Service]
#Type=forking -B
#PIDFile=/tmp/flowentryd.pid
#ExecStart=/usr/local/zjmf/cloud/apps/flowentryd
#ExecReload=
#ExecStop=/bin/kill -WINCH
#PrivateTmp=true
#
#[Install]
#WantedBy=multi-user.target
#EOF
#systemctl daemon-reload
#systemctl start flowentryd
#systemctl enable flowentryd
#  fi
#else
if [ `grep "supervisord" /usr/lib/systemd/system/flowentryd.service |wc -l` -ne 0 -o ! -e "/usr/lib/systemd/system/flowentryd.service" ];then
cat > /usr/lib/systemd/system/flowentryd.service <<EOF
[Unit]
Description=OpenFlow Entries Daemon
After=openvswitch.service

[Service]
Type=forking -B
PIDFile=/tmp/flowentryd.pid
ExecStart=/usr/local/zjmf/cloud/apps/flowentryd
ExecReload=
ExecStop=/bin/kill -WINCH
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl restart flowentryd
systemctl enable flowentryd
fi
#fi

# version 2.2.0
for i in `ip netns list |grep -oE vpc_[0-9]+`;do
  ns_id=$(ip netns exec $i ip a show |grep int |grep 172.16 |head -n 1|awk '{print $NF}' |awk -F'_' '{print $2}')
  if [ -n "$ns_id" ];then
    if [ $(ip netns exec vpc_${ns_id} ip a show |grep ifb |wc -l) -eq 0 ];then
      ip netns exec vpc_${ns_id} ip link add ifb0 type ifb
      ip netns exec vpc_${ns_id} ip link set ifb0 up
    fi
  fi
done

#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ $(grep "chmod" /etc/supervisord.conf |wc -l) -eq 0 ];then
#cat > /etc/supervisord.conf << 'EOF'
#[unix_http_server]
#file=/var/run/supervisor/supervisor.sock
#chmod=0777
#[supervisord]
#logfile=/var/log/supervisor/supervisord.log
#logfile_maxbytes=50MB
#logfile_backups=10
#loglevel=info
#pidfile=/var/run/supervisord.pid
#nodaemon=false
#minfds=1024
#minprocs=200
#[rpcinterface:supervisor]
#supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
#[supervisorctl]
#serverurl=unix:///var/run/supervisor/supervisor.sock
#[include]
#files = /etc/supervisord.d/*.ini
#EOF
#  fi
#fi

function install_package(){
  rpm_package=$1
  rpm -ivh http://mirror.cloud.idcsmart.com/cloud/RPMS/$rpm_package --nodeps --force
}
yum list installed rsync || install_package "rsync-3.1.2-10.el7.x86_64.rpm"

pip3 list |grep aria2p || check="false"
if [ "$check" = "false" ]; then
    mkdir -p /home/zjmf/download
    aria2c -x 2 http://mirror.cloud.idcsmart.com/cloud/compute/python3-packages.tar.gz -d /home/zjmf/download
    tar zxf /home/zjmf/download/python3-packages.tar.gz -C /home/zjmf/download
    pip3 install /home/zjmf/download/python3-packages/*.whl
    rm -rf /home/zjmf/download
fi

# version 2.3.0
if [ `rpm -qa |grep haproxy |wc -l` -eq 0 ];then
  rpm -ivh http://mirror.cloud.idcsmart.com/cloud/compute/rpms/haproxy-1.5.18-9.el7.x86_64.rpm --nodeps > /dev/null 2>&1
fi

# version 2.3.1
if [ `ip netns |grep vpc_100101 |wc -l` -ne 0 ];then
  external_ip=`grep external_ip /usr/local/zjmf/conf/net.conf |awk -F'=' '{print $2}'`
  ip netns exec vpc_100101 iptables -t nat -D PREROUTING -d $external_ip/32 -j DNAT --to-destination 172.31.255.254
  if [ `ip netns exec vpc_100101 iptables-save |grep "dports 80:443 -j DNAT --to-destination 172.31.255.254" |wc -l` -eq 0 ];then
    ip netns exec vpc_100101 iptables -t nat -A PREROUTING -d $external_ip/32 -p tcp -m multiport ! --dports 80:443 -j DNAT --to-destination 172.31.255.254
  fi
fi

if [ `rpm -qa |grep pyOpenSSL |wc -l` -eq 0 ];then
  rpm -ivh http://mirror.cloud.idcsmart.com/cloud/compute/rpms/pyOpenSSL-0.13.1-4.el7.x86_64.rpm --nodeps > /dev/null 2>&1
fi

# version 2.3.6
if [ ! -f /usr/local/zjmf/bin/node_exporter ];then
  aria2c -x 2 http://mirror.cloud.idcsmart.com/cloud/compute/node_exporter -d /usr/local/zjmf/bin
  chmod +x /usr/local/zjmf/bin/node_exporter
  if [ ! -f /usr/lib/systemd/system/node_exporter.service ];then
cat > /usr/lib/systemd/system/node_exporter.service <<EOF
[Unit]
Description=Prometheus node_exporter

[Service]
Type=forking -B
PIDFile=/tmp/node_exporter.pid
ExecStart=/usr/local/zjmf/bin/node_exporter
ExecReload=
ExecStop=/bin/kill -WINCH
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
  fi
fi

# version 2.3.9
#cat > /var/spool/cron/root << EOF
## contab
#0 * * * * ntpdate -u cn.pool.ntp.org > /dev/null 2>&1
#* * * * * /usr/bin/php /usr/local/zjmf/php/oneMinute.php > /dev/null 2>&1
#* * * * * /usr/local/zjmf/bin/ddnspod -f /usr/local/zjmf/conf/dnspod.conf > /dev/null 2>&1
#EOF
if [ $(grep 'ntpdate -u cn.pool.ntp.org' /var/spool/cron/root |wc -l) -eq 0 ];then
  echo '0 * * * * ntpdate -u cn.pool.ntp.org > /dev/null 2>&1' >> /var/spool/cron/root
fi
if [ $(grep '/usr/bin/php /usr/local/zjmf/php/oneMinute.php' /var/spool/cron/root |wc -l) -eq 0 ];then
  echo '* * * * * /usr/bin/php /usr/local/zjmf/php/oneMinute.php > /dev/null 2>&1' >> /var/spool/cron/root
fi
if [ $(grep '/usr/local/zjmf/bin/ddnspod -f /usr/local/zjmf/conf/dnspod.conf' /var/spool/cron/root |wc -l) -eq 0 ];then
  echo '* * * * * /usr/local/zjmf/bin/ddnspod -f /usr/local/zjmf/conf/dnspod.conf > /dev/null 2>&1' >> /var/spool/cron/root
fi

# version 2.4.4
if [ $(ovs-vsctl list Controller phy-ext |grep inactivity_probe |grep 60000 |wc -l) -eq 0 ];then
  ovs-vsctl set Controller phy-ext inactivity_probe=60000
  ovs-vsctl set Controller ovs-ext inactivity_probe=60000
  ovs-vsctl set Controller ovs-tun inactivity_probe=60000
  uuid=$(ovs-vsctl list Manager |grep uuid |awk '{print $3}')
  ovs-vsctl set Manager $uuid inactivity_probe=30000
fi

# version 2.5.6
#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#cat > /etc/supervisord.d/api-compute.ini <<EOF
#[program:api-compute]
#command=/usr/bin/python2 /usr/local/zjmf/cloud/api_load.py
#directory=/usr/local/zjmf/cloud
#priority=1
#numprocs=1
#autostart=true
#autorestart=true
#startretries=10
#stopasgroup=true
#stopsignal=KILL
#stopwaitsecs=10
#redirect_stderr=true
#stdout_logfile=/var/log/supervisor/api-compute.log
#EOF
#  supervisorctl update api-compute
#  supervisorctl restart api-compute
#fi

# version 2.9.1
#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ ! -e "/etc/supervisord.d/api.ini" ];then
#supervisorctl stop api-go
#cat > /etc/supervisord.d/api.ini << 'EOF'
#[program:api-go]
#command=/usr/local/zjmf/bin/api
#directory=/usr/local/zjmf/bin
#priority=1
#numprocs=1
#autostart=true
#autorestart=true
#startretries=10
#stopasgroup=true
#stopsignal=KILL
#stopwaitsecs=10
#redirect_stderr=true
#EOF
#supervisorctl update
#supervisorctl restart api-go
#  fi
#fi

if [ ! -f "/usr/local/zjmf/conf/ksmtuned.conf" ];then
cat > /usr/local/zjmf/conf/ksmtuned.conf << 'EOF'
KSM_THRES_COEF=95
KSM_SLEEP_MSEC=30
USE_ZERO_PAGES=0
EOF
fi

#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ ! -f "/etc/supervisord.d/ksmtuned.ini" ];then
#chmod +x /usr/local/zjmf/bin/ksmtuned
#cat > /etc/supervisord.d/ksmtuned.ini << 'EOF'
#[program:ksmtuned]
#command=/usr/local/zjmf/bin/ksmtuned
#directory=/usr/local/zjmf/bin
#priority=1
#numprocs=1
#autostart=true
#autorestart=true
#startretries=10
#stopasgroup=true
#stopsignal=KILL
#stopwaitsecs=10
#redirect_stderr=true
#stdout_logfile=/var/log/supervisor/ksmtuned.log
#EOF
#supervisorctl update
#supervisorctl restart ksmtuned
#supervisorctl restart api-go
#  fi
#fi

sed -i '/^HWADDR.*/Id' /etc/sysconfig/network-scripts/ifcfg-phy-ext
sed -i '/^UUID/Id' /etc/sysconfig/network-scripts/ifcfg-phy-ext

if [ ! -f "/usr/local/zjmf/cloud/network/datapath.db" ];then
  aria2c -x 2 http://mirror.cloud.idcsmart.com/cloud/compute/datapath.db -d /usr/local/zjmf/cloud/network
  chown qemu.qemu /usr/local/zjmf/cloud/network/datapath.db
fi

# version 2.7.0
# ovs-ofctl add-flow ovs-ext "table=0,priority=4,in_port="oext-to-pext" actions=drop"

# version 2.8.5
if [ `ovs-vsctl get-fail-mode phy-ext |grep secure |wc -l` -eq 0 ];then
  ovs-vsctl set-fail-mode phy-ext secure
  ovs-vsctl set-fail-mode ovs-ext secure
  ovs-vsctl set-fail-mode ovs-tun secure
fi

# version 3.0.0
[ -f "/usr/lib/systemd/system/adsl.service" ] && systemctl restart adsl

# version 3.0.0
ovs-ofctl add-flow ovs-ext "table=0,priority=5,in_port=1,ip6 actions=mod_vlan_vid:100,resubmit(,60)"
systemctl restart flowentryd

# version 3.0.9
# for light node
if [ `ovs-vsctl list-br |grep phy-ext |wc -l` -eq 0 ];then
  if [ ! -f /etc/libvirt/nwfilter/no-ipv6-spoofing.xml ];then
cat > /etc/libvirt/nwfilter/no-ipv6-spoofing.xml <<'EOF'
<filter name='no-ipv6-spoofing' chain='ipv6-ip' priority='-610'>
  <rule action='return' direction='out' priority='100'>
    <ipv6 srcipaddr='fe80::' srcipmask='10' protocol='udp'/>
  </rule>
  <rule action='return' direction='out' priority='500'>
    <ipv6 srcipaddr='$IPV6'/>
  </rule>
  <rule action='drop' direction='out' priority='1000'/>
</filter>
EOF
    virsh nwfilter-define /etc/libvirt/nwfilter/no-ipv6-spoofing.xml
  fi
  if [ ! -f /etc/libvirt/nwfilter/allow-incoming-ipv6.xml ];then
cat > /etc/libvirt/nwfilter/allow-incoming-ipv6.xml <<EOF
<filter name='allow-incoming-ipv6' chain='ipv6' priority='-600'>
  <rule action='accept' direction='in' priority='500'/>
</filter>
EOF
    virsh nwfilter-define /etc/libvirt/nwfilter/allow-incoming-ipv6.xml
  fi
  if [ ! -f /etc/libvirt/nwfilter/allow-dhcpv6.xml ];then
cat > /etc/libvirt/nwfilter/allow-dhcpv6.xml <<EOF
<filter name='allow-dhcpv6' chain='ipv6' priority='-600'>
  <rule action='accept' direction='out' priority='100'>
    <ipv6 srcipaddr='fe80::' srcipmask='10' dstipaddr='ff02::1:2' protocol='udp' srcportstart='546' dstportstart='547'/>
  </rule>
  <rule action='accept' direction='in' priority='100'>
    <ipv6 protocol='udp' srcportstart='547' dstportstart='546'/>
  </rule>
</filter>
EOF
    virsh nwfilter-define /etc/libvirt/nwfilter/allow-dhcpv6.xml
  fi
  if [ ! -f /etc/libvirt/nwfilter/clean-traffic-ipv6.xml ];then
cat > /etc/libvirt/nwfilter/clean-traffic-ipv6.xml <<EOF
<filter name='clean-traffic-ipv6' chain='root'>
  <filterref filter='no-mac-spoofing'/>
  <filterref filter='no-ipv6-spoofing'/>
  <rule action='accept' direction='out' priority='-600'>
    <mac protocolid='ipv6'/>
  </rule>
  <filterref filter='allow-incoming-ipv6'/>
  <filterref filter='allow-dhcpv6'/>
  <filterref filter='no-other-l2-traffic'/>
</filter>

EOF
    virsh nwfilter-define /etc/libvirt/nwfilter/clean-traffic-ipv6.xml
  fi
fi

# 3.4.8
TIMEOUT=$(cat /etc/httpd/conf/httpd.conf |grep "TimeOut")
if [ "$ID" = "centos" -a "$VERSION" = "8" -a "$TIMEOUT" != "TimeOut 1800" ]; then
cat > /etc/httpd/conf/httpd.conf << 'EOF'
ServerRoot "/etc/httpd"
Include conf.modules.d/*.conf
User qemu
Group qemu
TimeOut 1800
ServerAdmin root@localhost
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>
<Files ".ht*">
    Require all denied
</Files>
ErrorLog "logs/error_log"
LogLevel warn
<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>
    CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>
<IfModule mime_module>
    TypesConfig /etc/mime.types
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>
AddDefaultCharset UTF-8
<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>
EnableSendfile on
IncludeOptional conf.d/*.conf
EOF
systemctl restart httpd
fi

# 3.5.11
if [ "$ID" = "centos" -a "$VERSION" = "7 (Core)" -a ! -d /usr/local/qemu/5.2.0 ]; then
mkdir -p /home/zjmf/download
aria2c http://mirror.cloud.idcsmart.com/cloud/compute/qemu-rpms.tar.gz -d /home/zjmf/download
tar zxf /home/zjmf/download/qemu-rpms.tar.gz -C /home/zjmf/download
cd /home/zjmf/download/qemu-rpms
for rpms in $(ls); do rpm -Uvh --nodeps --nosignature $rpms; done
aria2c http://mirror.cloud.idcsmart.com/cloud/compute/qemu-5.2.0.tar.gz -d /home/zjmf/download
mkdir -p /usr/local/qemu/
tar zxf /home/zjmf/download/qemu-5.2.0.tar.gz -C /usr/local/qemu/
fi

#which supervisorctl > /dev/null 2>&1
#if [ $? -eq 0 ];then
#  if [ ! -f "/etc/supervisord.d/updaemon-compute-new.ini" ];then
#cat > /etc/supervisord.d/updaemon-compute-new.ini <<EOF
#[program:updaemon-compute-new]
#command=/usr/bin/python /usr/local/zjmf/cloud/apps/updaemon_new.py
#directory=/usr/local/zjmf/cloud/apps
#priority=1
#numprocs=1
#autostart=true
#autorestart=true
#startretries=10
#stopasgroup=true
#stopsignal=KILL
#stopwaitsecs=10
#redirect_stderr=true
#stdout_logfile=/var/log/supervisor/updaemon-compute.log
#EOF
#supervisorctl update updaemon-compute-new
#supervisorctl start updaemon-compute-new
#  fi
#fi

which conntrack > /dev/null 2>&1
if [ $? -ne 0 -a "$VERSION_ID" == "7" -a `rpm -qa |grep conntrack-tools |wc -l` -eq 0 ];then
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/conntrack-tools-1.4.4-7.el7.x86_64.rpm -d /root
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/libnetfilter_cthelper-1.0.0-11.el7.x86_64.rpm -d /root
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/libnetfilter_cttimeout-1.0.0-7.el7.x86_64.rpm -d /root
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/libnetfilter_queue-1.0.2-2.el7_2.x86_64.rpm -d /root

  rpm -ivh /root/conntrack-tools-1.4.4-7.el7.x86_64.rpm --nodeps
  rpm -ivh /root/libnetfilter_cthelper-1.0.0-11.el7.x86_64.rpm --nodeps
  rpm -ivh /root/libnetfilter_cttimeout-1.0.0-7.el7.x86_64.rpm --nodeps
  rpm -ivh /root/libnetfilter_queue-1.0.2-2.el7_2.x86_64.rpm --nodeps

  rm -rf /root/conntrack-tools-1.4.4-7.el7.x86_64.rpm
  rm -rf /root/libnetfilter_cthelper-1.0.0-11.el7.x86_64.rpm
  rm -rf /root/libnetfilter_cttimeout-1.0.0-7.el7.x86_64.rpm
  rm -rf /root/libnetfilter_queue-1.0.2-2.el7_2.x86_64.rpm

elif [ $? -ne 0 -a "$VERSION_ID" == "8" -a `rpm -qa |grep conntrack-tools |wc -l` -eq 0 ];then
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/libnetfilter_cthelper-1.0.0-15.el8.x86_64.rpm  -d /root
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/libnetfilter_cttimeout-1.0.0-11.el8.x86_64.rpm -d /root
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/libnetfilter_queue-1.0.4-3.el8.x86_64.rpm -d /root
  aria2c http://mirror.cloud.idcsmart.com/cloud/software/conntrack-tools-1.4.4-10.el8.x86_64.rpm -d /root

  rpm -ivh /root/libnetfilter_cthelper-1.0.0-15.el8.x86_64.rpm --nodeps
  rpm -ivh /root/libnetfilter_cttimeout-1.0.0-11.el8.x86_64.rpm --nodeps
  rpm -ivh /root/libnetfilter_queue-1.0.4-3.el8.x86_64.rpm --nodeps
  rpm -ivh /root/conntrack-tools-1.4.4-10.el8.x86_64.rpm --nodeps

  rm -rf /root/libnetfilter_cthelper-1.0.0-15.el8.x86_64.rpm
  rm -rf /root/libnetfilter_cttimeout-1.0.0-11.el8.x86_64.rpm
  rm -rf /root/libnetfilter_queue-1.0.4-3.el8.x86_64.rpm
  rm -rf /root/conntrack-tools-1.4.4-10.el8.x86_64.rpm
fi

# 3.6.13
if [ ! -e "/usr/lib/systemd/system/updaemon_compute.service" ];then
cat > /usr/lib/systemd/system/updaemon_compute.service <<EOF
[Unit]
Description=Daemon For Zjmf Compute Update
Before=rc-local.service
After=nss-user-lookup.target

[Service]
Type=forking -B
PIDFile=/tmp/updaemon_compute.pid
ExecStart=/usr/local/zjmf/cloud/apps/updaemon_compute

[Install]
WantedBy=multi-user.target
EOF
#supervisorctl stop updaemon_compute
#[ -e "/etc/supervisord.d/updaemon-compute.ini" ] && mv /etc/supervisord.d/updaemon-compute.ini /tmp
#supervisorctl update
chmod 755 -R /usr/local/zjmf/cloud/apps
systemctl daemon-reload
systemctl start updaemon_compute
systemctl enable updaemon_compute
fi

if [ ! -e "/usr/lib/systemd/system/ryu-manager.service" ];then
cat > /usr/lib/systemd/system/ryu-manager.service <<EOF
[Unit]
Description=The Ryu Manager
Before=openvswitch.service

[Service]
Type=simple
ExecStart=/usr/bin/python2.7 /usr/bin/ryu-manager /usr/local/zjmf/cloud/network/switch.py /usr/lib/python2.7/site-packages/ryu/app/ofctl_rest.py --verbos --wsapi-host 127.0.0.1 --ofp-listen-host 127.0.0.1
Restart=always

[Install]
WantedBy=multi-user.target
EOF
systemctl restart flowentryd
supervisorctl stop ryu-manager
[ -e "/etc/supervisord.d/ryu-manager.ini" ] && mv /etc/supervisord.d/ryu-manager.ini /tmp
supervisorctl update
systemctl daemon-reload
systemctl start ryu-manager
systemctl enable ryu-manager
fi

if [ ! -e "/lib/systemd/system/api-compute.service" ];then
cat > /lib/systemd/system/api-compute.service << 'EOF'
[Unit]
Description=Zjmf Compute Python API
Before=rc-local.service

[Service]
Type=simple
WorkingDirectory=/usr/local/zjmf/cloud
ExecStart=/usr/bin/python2 /usr/local/zjmf/cloud/api_load.py

[Install]
WantedBy=multi-user.target
EOF
supervisorctl stop api-compute
[ -e "/etc/supervisord.d/api-compute.ini" ] && mv /etc/supervisord.d/api-compute.ini /tmp
supervisorctl update
systemctl daemon-reload
systemctl start api-compute
systemctl enable api-compute
fi

if [ -e "/etc/supervisord.d/api.ini" ];then
  supervisorctl stop api-go
  mv /etc/supervisord.d/api.ini /tmp
  supervisorctl update
fi

if [ ! -e "/lib/systemd/system/api-node.service" ];then
cat > /lib/systemd/system/api-node.service << 'EOF'
[Unit]
Description=Zjmf Compute Go API
Requires=network.target
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/zjmf/bin/api

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start api-node
systemctl enable api-node
fi

if [ -e "/etc/supervisord.d/aria2.ini" ];then
  supervisorctl stop aria2
  mv /etc/supervisord.d/aria2.ini /tmp
  supervisorctl update
fi

if [ ! -e "/lib/systemd/system/aria2-node.service" ];then
cat > /lib/systemd/system/aria2-node.service << 'EOF'
[Unit]
Description=zjmf aria2-node program
Requires=network.target
After=network.target

[Service]
Type=simple
User=qemu
Group=qemu
ExecStart=/usr/local/zjmf/bin/aria2c --conf-path=/usr/local/zjmf/conf/aria2.conf

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start aria2-node
systemctl enable aria2-node
fi

if [ -e "/etc/supervisord.d/ksmtuned.ini" ];then
  supervisorctl stop ksmtuned
  mv /etc/supervisord.d/ksmtuned.ini /tmp
  supervisorctl update
fi

if [ ! -e "/lib/systemd/system/ksmmgr.service" ];then
cat > /lib/systemd/system/ksmmgr.service << 'EOF'
[Unit]
Description=zjmf ksmmgr program
Requires=network.target
After=network.target

[Service]
Type=forking -B
PIDFile=/run/ksmtuned-go.pid
WorkingDirectory=/usr/local/zjmf/bin
ExecStart=/usr/local/zjmf/bin/ksmtuned

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start ksmmgr
systemctl enable ksmmgr
fi

if [ -e "/etc/supervisord.d/crontab.ini" ];then
  supervisorctl stop crontab
  mv /etc/supervisord.d/crontab.ini /tmp
  supervisorctl update
fi

# if [ -e "/etc/php-fpm.d/www-nginx.conf" ];then
# sed -i '/pm.max_children/ s|64|256|g' /etc/php-fpm.d/www-nginx.conf
# sed -i '/pm.start_servers/ s|6|16|g' /etc/php-fpm.d/www-nginx.conf
# sed -i '/pm.min_spare_servers/ s|6|16|g' /etc/php-fpm.d/www-nginx.conf
# sed -i '/pm.max_spare_servers/ s|64|256|g' /etc/php-fpm.d/www-nginx.conf
# systemctl restart php-fpm
# fi

if [ -e "/etc/php-fpm.d/www.conf" ];then
  rm -f /etc/php-fpm.d/www.conf
cat > /etc/php-fpm.d/www-node.conf <<EOF
[www-node]
user = qemu
group = qemu
listen = /run/php-fpm/www.sock
listen.acl_users = qemu
listen.allowed_clients = 127.0.0.1
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
slowlog = /var/log/php-fpm/www-slow.log
php_admin_value[error_log] = /var/log/php-fpm/www-node-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/lib/php/session
php_value[soap.wsdl_cache_dir]  = /var/lib/php/wsdlcache
EOF
systemctl restart php-fpm
fi

if [ `grep "/usr/local/zjmf/cloud/apps/boot_all_host.php" /etc/rc.d/rc.local |wc -l` -eq 1 ];then
  sed -i 's#/usr/local/zjmf/cloud/apps/boot_all_host.php#/usr/local/zjmf/php/boot_all_host.php#g' /etc/rc.d/rc.local
fi

# 3.6.17
modprobe 8021q
[ ! -f /etc/modules-load.d/8021q.conf ] && echo "8021q" > /etc/modules-load.d/8021q.conf

if [ -f /usr/bin/supervisorctl ];then
  mv /usr/bin/supervisorctl /usr/bin/supervisorctl.bak
  systemctl restart api-compute
  systemctl restart ksmmgr
  systemctl restart api-node
  systemctl restart aria2-node
fi

if [ $(grep "flowentryd_version=3" /usr/local/zjmf/conf/zjmf.conf |wc -l) -eq 0 ];then
  if [ $(grep "flowentryd_version=2" /usr/local/zjmf/conf/zjmf.conf |wc -l) -eq 0 ];then
    sed -i '/cls_int_vlan_tag/aflowentryd_version=3' /usr/local/zjmf/conf/zjmf.conf
  else
    sed -i 's/flowentryd_version=2/flowentryd_version=3/g' /usr/local/zjmf/conf/zjmf.conf
  fi
  systemctl restart flowentryd
fi

# reset_password and multi_ip_forward permissions and sudoers
chmod -R +x /usr/local/zjmf/cloud/apps/reset_password/
chmod -R +x /usr/local/zjmf/cloud/apps/multi_ip_forward/
chown -R qemu.qemu /usr/local/zjmf/cloud/apps/reset_password/
chown -R qemu.qemu /usr/local/zjmf/cloud/apps/multi_ip_forward/
grep -q '/usr/local/zjmf/cloud/apps/reset_password/' /etc/sudoers || sed -i '/^Cmnd_Alias[[:space:]]\+CLOUD[[:space:]]*=/ s/$/, \/usr\/local\/zjmf\/cloud\/apps\/reset_password\//' /etc/sudoers
grep -q '/usr/local/zjmf/cloud/apps/multi_ip_forward/' /etc/sudoers || sed -i '/^Cmnd_Alias[[:space:]]\+CLOUD[[:space:]]*=/ s/$/, \/usr\/local\/zjmf\/cloud\/apps\/multi_ip_forward\//' /etc/sudoers

# add 50-libvirt-qemu.rules file for reset_password
sudo mkdir -p /etc/polkit-1/rules.d
sudo tee /etc/polkit-1/rules.d/50-libvirt-qemu.rules > /dev/null << 'EOF'
polkit.addRule(function(action, subject) {
    if (action.id == "org.libvirt.unix.manage" &&
        (subject.isInGroup("libvirt") || subject.user == "qemu")) {
        return polkit.Result.YES;
    }
});
EOF

chmod 644 /etc/polkit-1/rules.d/50-libvirt-qemu.rules
usermod -aG libvirt qemu

# multi_ip_forward for /etc/sudoers.d/99-multi-ip-forward-qemu
sudo tee /etc/sudoers.d/99-multi-ip-forward-qemu > /dev/null << 'EOF'
# multi_ip_forward: qemu 网络操作（root 执行 setup-qemu-user.sh 生成）
qemu ALL=(root) NOPASSWD: /usr/local/zjmf/cloud/network/network_service.py *
qemu ALL=(root) NOPASSWD: /usr/sbin/ip *
qemu ALL=(root) NOPASSWD: /sbin/ip *
qemu ALL=(root) NOPASSWD: /usr/sbin/iptables *
qemu ALL=(root) NOPASSWD: /usr/sbin/iptables-save *
qemu ALL=(root) NOPASSWD: /usr/sbin/conntrack *
qemu ALL=(root) NOPASSWD: /usr/bin/ovs-vsctl *
qemu ALL=(root) NOPASSWD: /usr/bin/ovs-ofctl *
qemu ALL=(root) NOPASSWD: /sbin/ifup *
qemu ALL=(root) NOPASSWD: /sbin/ifdown *
qemu ALL=(root) NOPASSWD: /usr/bin/systemctl *
qemu ALL=(root) NOPASSWD: /usr/local/zjmf/cloud/apps/multi_ip_forward/multi_ip_forward.sh *
qemu ALL=(root) NOPASSWD: /usr/local/zjmf/cloud/apps/tools *
qemu ALL=(root) NOPASSWD: /usr/bin/systemctl restart network
EOF

chmod 440 /etc/sudoers.d/99-multi-ip-forward-qemu
chown root:root /etc/sudoers.d/99-multi-ip-forward-qemu

chown -R qemu.qemu /usr/local/zjmf/cloud/apps/multi_ip_forward/
chmod +x /usr/local/zjmf/cloud/apps/multi_ip_forward/*.sh

rm -rf /usr/local/zjmf/update_scripts.sh
