#!/bin/sh

usage(){
  cat <<EOF
SkyCover Infrastructure cluster distribution setup utility
For more information refer http://www.skycover.ru/products/sci-cd

Usage:

1. Setup backbone interface (on both nodes)
* Plug in backbone (to another node or to the backbone switch)
# sci-setup backbone [-f]

with -f the old backbone record will be overriden.
 USE ONLY BEFORE CLUSTER IS SET UP!

2. Setup cluster
# sci-setup cluster [-i CLUSTER_IP] [-c CLUSTER_NAME] [-n NODE2_IP] [-s]

CLUSTER_IP defaults to sci.conf else to interlink .10 and will be prompted
CLUSTER_NAME defaults sci.conf else guessed from node1 name
with -s (single) one-node install is performed
without -s operation is possible if:
 * backbone IP is .11 and there is ping to .12 which will be node2
 * or NODE2_IP is preset in sci.conf or feed in via -v
 In both situations NODE2 hostname and NODE2 lan IP will be checked via ssh
 NODE2 hostname should have prefix part like NODE1 hostname
EOF
}

# usage check_ip IP
# returns NETDEV MASK or exits with error
check_ip(){
  /sbin/ifconfig|awk -vip="$1" '
/^[a-z]/{iface=$1}
/^[ \t]*inet /{
  addr=$2
  if(addr == ip){
    for(i=1; i<=NF; i++){
      if($i ~ /^netmask.*/){
        split($0,M," ")
        mask=M[4]
      }
    }
    print iface, mask
    ok = 1
    exit
  }
}
END{
  if(ok)exit 0
  exit 1
}
' || (cat <<EOF 1>&2
ERROR!
The IP address $1 is NOT UP on the node!
Check ifconfig, /etc/network/interfaces and /etc/sci/sci.conf

Aborting.
EOF
  exit 1)
}

# usage: check_netdev IFACE PURPOSE
# exits with error
check_netdev(){
  if ! grep -q "^iface `echo $1|cut -d ':' -f 1`" /etc/network/interfaces; then
   cat <<EOF
ERROR!
The interface $1 as $2 should be configured and up!
Check /etc/network/interfaces and /etc/sci/sci.conf

Aborting.
EOF
   exit 1
  fi
  if ! /sbin/ifconfig|grep -q "^`echo $1|cut -d ':' -f 1`"; then
   cat <<EOF
ERROR!
The interface $1 as $2 seems configured but NOT UP!
Check ifconfig, /etc/network/interfaces and /etc/sci/sci.conf

Aborting.
EOF
   exit 1
  fi
}

# check_ip_net IP1 IP2 IP2-MASK
# return 0 if IP1 in the same network as IP2
check_ip_net(){
  m1=`ipcalc -n $1 $3|awk '/^Network:/{print $2}'`
  m2=`ipcalc -n $2 $3|awk '/^Network:/{print $2}'`
  test "$m1" = "$m2"
}

# Create line for /etc/ganeti networks
# Args: IP NETMASK INTERFACE
for_networks(){
  N_NETWORK=`ipcalc -n $1 $2|awk -F"[: /]+" '/^Network:/{print $2; exit 0}'`
  N_NETMASK=`ipcalc -n $1 $2|awk -F"[: /]+" '/^Netmask:/{print $2; exit 0}'`
  N_BROADCAST=`ipcalc -n $1 $2|awk -F"[: /]+" '/^Broadcast:/{print $2; exit 0}'`
  if [ -n "$3" ]; then
    N_GATEWAY=`ip route |grep "^default via .* dev $3"|cut -d' ' -f 3`
  else
    N_GATEWAY=""
  fi
  echo $N_NETWORK $N_NETMASK $N_BROADCAST $N_GATEWAY
}

# Check for reinstall
if [ -f /etc/should-reinstall ]; then
  cat <<EOF
The server was not properly installed
The following errors cause furhter improper configuration which is fatal:

`cat /etc/should-reinstall`

Please reinstall the server
EOF
  exit 1
fi

if [ "$#" -eq 0 ]; then
  usage
  exit 1
fi

. /etc/sci/sci.conf

SCI_NAME="sci"

# Guess hostname, DOMAIN_NAME

#hostname=`head -1 $target/etc/hostname`
hostname=`hostname`

#DOMAIN_NAME=`grep $hostname $target/etc/hosts|awk '{sub("^[^.]*\.","",$2); print $2}'`
DOMAIN_NAME=`dnsdomainname`

case $1 in

cluster)

shift

#### Perform some AI

# Guess NODE1_NAME, NODE1_LAN_IP
# Check NODE1_IP against ifconfig
# Get NODE1_NETDEV NODE1_MASK
# Check NODE1_NETDEV against interfaces

# Check NODE1_LAN_IP against ifconfig
# Get NODE1_LAN_NETDEV NODE1_LAN_MASK
# Check NODE1_LAN_NETDEV against interfaces

# Guess CLUSTER_NAME
# Guess or prompt CLUSTER_IP
# Check CLUSTER_IP against NODE1_LAN_x and NODE1_INT_x, try to find CLU_NETDEV, or set to MASTER_NETDEV
# Check autodetected CLU_NETDEV against MASTER_NETDEV override, abort if not match
# Set MASTER_NETDEV to match CLU_NETDEV
# Check LAN_NETDEV against NODE1_LAN_NETDEV and NODE1_NETDEV
# Set LAN_NETDEV or pass

short_hostname=`echo $hostname|sed -E 's/^([^.]*).*/\1/'`
if [ -z "$NODE1_NAME" ]; then
  NODE1_NAME=$short_hostname
  nodenum=`echo $hostname|sed -E 's/^[^.]*[^0-9]([0-9]+)\.?.*/\1/'`
  if [ -z "$nodenum" -o "$nodenum" != 1 ]; then
    echo Node name must ends with number 1. Aborting.
    exit 1
  fi
else
  if [ "$NODE1_NAME" != "$short_hostname" ]; then
    echo NODE1_NAME in config '"'$NODE1_NAME'"' not matching hostname short part '"'$short_hostname'"'. Aborting.
    exit 1
  fi
fi

read NODE1_NETDEV NODE1_MASK <<EOF
`check_ip $NODE1_IP`
EOF

# correct variable
NODE1_NETDEV=`echo $NODE1_NETDEV|cut -d ':' -f 1`
check_netdev $NODE1_NETDEV NODE1_NETDEV

if [ -z "$NODE1_LAN_IP" ]; then
  # get lan IP from hosts
  #NODE1_LAN_IP=`grep $hostname $target/etc/hosts|awk '{print $1}'`
  NODE1_LAN_IP=`ip addr show lan|awk -F'[ /]+' '/inet /{print $3;exit}'`
fi

if [ -n "$NODE1_LAN_IP" ]; then
  read NODE1_LAN_NETDEV NODE1_LAN_MASK <<EOF
`check_ip $NODE1_LAN_IP`
EOF
  # correct variable
  NODE1_LAN_NETDEV=`echo $NODE1_LAN_NETDEV|cut -d ':' -f 1`
  check_netdev $NODE1_LAN_NETDEV NODE1_LAN_NETDEV
  if [ "`echo $NODE1_LAN_NETDEV|cut -d ':' -f 1`" != "lan" ]; then
    echo Network device for LAN should be named '"'lan'"', but got '"'$NODE1_LAN_NETDEV'"'. Aborting.
    exit 1
  fi
fi

while getopts "i:c:n:s" opt; do
  case $opt in
    i)
        CLUSTER_IP=$OPTARG
    ;;
    c)
        CLUSTER_NAME=$OPTARG
    ;;
    n)
        NODE2_IP=$OPTARG
    ;;
    s)
        SINGLE_MODE="yes"
        NODE2_IP=""
    ;;
  esac
done

BASE_NAME=`echo $hostname|sed -E 's/^([^.]*[^0-9])[0-9]+\.?.*/\1/'`
if [ -z "$CLUSTER_NAME" ]; then
  CLUSTER_NAME=`echo $BASE_NAME|sed 's/-$//'`
fi

# (xend-relocation-hosts-allow '^localhost$ ^testing[0-9]+\\.test\\.ru$')
reloc_domain=`awk -v d="$DOMAIN_NAME" 'BEGIN{gsub("[.]","\\\\\\\\\\\\\\\\.",d);print d; exit}'`
sed -i 's/^(xend-relocation-hosts-allow .*/(xend-relocation-hosts-allow '"'^localhost$ ^$BASE_NAME[0-9]+\\\\\\\\.$reloc_domain\$')/" /etc/xen/xend-config.sxp
service xen restart

# lang and timezone choose
echo "Current locale: $LOCALE"
echo "Current timezone: $TIMEZONE"
echo "If you want to change it, write \"yes\""
echo "Otherwise press ENTER"
read lang_set
if [ "$lang_set" = "yes" ]; then
  LANG=C dpkg-reconfigure locales
  LANG=C dpkg-reconfigure tzdata
  LOCALE=$(. /etc/default/locale;echo $LANG)
  TIMEZONE=$(cat /etc/timezone)
  echo $LOCALE
  echo $TIMEZONE
  sed -i 's/^LOCALE=.*/LOCALE='\"$LOCALE\"'/' /etc/sci/sci.conf
  sed -i 's/^TIMEZONE=.*/TIMEZONE='\"`echo $TIMEZONE|sed 's/\//\\\\\//'`\"'/' /etc/sci/sci.conf
fi


if [ -z "$SINGLE_MODE" -a -z "$NODE2_IP" ]; then
  NODE2_IP=`echo $NODE1_IP|cut -d . -f 1-3`.12
fi

if [ -z "$CLUSTER_IP" ]; then
  CLUSTER_IP=`echo $NODE1_IP|cut -d . -f 1-3`.10
  cluster_ip_guess="yes"
fi

if [ -n "$NODE1_LAN_IP" -a -n "$cluster_ip_guess" ]; then
  cat <<EOF
Cluster domain name will be $CLUSTER_NAME.
Cluster IP will be $CLUSTER_IP on the interlink.
We recommend to set it to some unbound LAN IP address,
but it is safe to simply press ENTER.
EOF
  while [ -z "$cluster_ip" ]; do
    if [ -n "$cluster_ip_guess" ]; then
      echo -n "Set cluster IP [$CLUSTER_IP]: "
      read cluster_ip
    fi
    test -z "$cluster_ip" && cluster_ip=$CLUSTER_IP
    if [ "$cluster_ip" = "$NODE1_LAN_IP" ]; then
      echo "Cluster IP should not be the same as node's IP"
      cluster_ip=""
    elif check_ip_net $cluster_ip $NODE1_LAN_IP $NODE1_LAN_MASK; then
      CLUSTER_IP=$cluster_ip
    elif check_ip_net $cluster_ip $NODE1_IP $NODE1_MASK; then
      CLUSTER_IP=$cluster_ip
    else
       echo $cluster_ip not in the LAN
       cluster_ip=""
    fi
    if [ -n "$cluster_ip" ]; then
      echo \\nChecking IP is free...
      if ping -q -c 1 $cluster_ip >/dev/null; then
        echo $cluster_ip is alive. It should be a free address!
        cluster_ip=""
      else
        echo ok
      fi
    fi
    test -z "$cluster_ip" -a -z "$cluster_ip_guess" && exit 1 # we're not interactive
  done
fi

if check_ip_net $CLUSTER_IP $NODE1_IP $NODE1_MASK; then
  CLU_NETDEV=$NODE1_NETDEV
  CLU_NETMASK=$NODE1_MASK
fi

if [ -n "$NODE1_LAN_IP" ]; then
  if check_ip_net $CLUSTER_IP $NODE1_LAN_IP $NODE1_LAN_MASK; then
    CLU_NETDEV=$NODE1_LAN_NETDEV
    CLU_NETMASK=$NODE1_LAN_MASK
  fi
fi

# correct variable
MASTER_NETDEV=`echo $MASTER_NETDEV|cut -d ':' -f 1`
test -n "$MASTER_NETDEV" && check_netdev $MASTER_NETDEV MASTER_NETDEV

if [ -n "$CLU_NETDEV" ]; then
  if [ -n "$MASTER_NETDEV" ]; then
    if [ "$CLU_NETDEV" != "$MASTER_NETDEV" ]; then
      cat <<EOF
ERROR!
The MASTER_NETDEV=$MASTER_NETDEV doesn't match autodetected device $CLU_NETDEV!
Check /etc/sci/sci.conf

Aborting.
EOF
      exit 1
    fi
  else
    MASTER_NETDEV=$CLU_NETDEV
    MASTER_NETMASK=$CLU_NETMASK
  fi
elif [ -z "$MASTER_NETDEV" ]; then
  cat <<EOF
ERROR!
Unable to figure out the MASTER_NETDEV!
The CLUSTER_IP=$CLUSTER_IP is not a part of configured NODE1 networks.
And the MASTER_NETDEV override not set.
Check /etc/sci/sci.conf

Aborting.
EOF
  exit 1
fi

# Here MASTER_NETDEV is always detected
MASTER_NETMASK=${MASTER_NETMASK:-"255.255.255.0"}

LAN_NETDEV=${LAN_NETDEV:-$NODE1_LAN_NETDEV}
LAN_NETDEV=${LAN_NETDEV:-$MASTER_NETDEV}

# Here LAN_NETDEV is always detected

#### End AI

if [ -n "$NODE2_IP" ]; then
  if check_ip_net $NODE2_IP $NODE1_IP $NODE1_MASK; then
    echo \\n\\nConnecting to Node2 via $NODE2_IP
    echo You will be prompted for a root password...\\n
    if ping -q -c 1 $NODE2_IP >/dev/null; then
      #NODE2_NAME=`ssh $NODE2_IP hostname|sed -E 's/^([^.]*[^0-9])[0-9]+\.?.*/\1/'`
      node2=`ssh -o GlobalKnownHostsFile=/tmp/known_hosts -o UserKnownHostsFile=/tmp/known_hosts $NODE2_IP  "hostname; ip addr show lan|awk -F'[ /]+' '/inet /{print \\\$3;exit}'"`
      rm /tmp/known_hosts
      NODE2_NAME_TEST=`echo $node2|awk '{print $1}'|sed -E 's/^([^.]*[^0-9])[0-9]+\.?.*/\1/'`
      NODE2_NAME=`echo $node2|awk '{print $1}'|awk -F. '{print $1}'`
      NODE2_LAN_IP=`echo $node2|awk '{print $2}'`
      if [ -z "$NODE2_NAME" ]; then
	echo Unable to get NODE2 name via ssh $NODE2_IP.
        echo Diagnostic is $node2
	echo Aborting.
	exit 1
      fi
      if [ "$NODE2_NAME" != "$BASE_NAME"2 ]; then
	echo NODE2 name must be "$BASE_NAME"2
        echo Current is $NODE2_NAME
	echo Aborting.
	exit 1
      fi
      if [ -z "$NODE2_LAN_IP" ]; then
	echo Unable to get NODE2 lan IP via ssh $NODE2_IP.
        echo Diagnostic is $node2
	echo Aborting.
	exit 1
      fi
    else
      echo Unable to reach NODE2 via $NODE2_IP. Aborting.
      exit 1
    fi
  else
    echo Node1 $NODE1_IP and Node2 $NODE2_IP are not on the same network. Aborting.
    exit 1
  fi
fi

cat <<EOF

########################################
Parameters detected:
Domain name: $DOMAIN_NAME

Master network interface: $MASTER_NETDEV

Cluster name: $CLUSTER_NAME
Cluster IP: $CLUSTER_IP
EOF
cat <<EOF

Node 1 name: $NODE1_NAME
Node 1 IP: $NODE1_IP
EOF
test -n "$NODE1_SAN_IP" && echo Node 1 SAN IP: $NODE1_SAN_IP
test -n "$NODE1_LAN_IP" && echo Node 1 LAN IP: $NODE1_LAN_IP
test -n "$LAN_NETDEDV" && echo LAN network interface: $LAN_NETDEV
echo ""

if [ -n "$NODE2_IP" ]; then
 if [ -n "$NODE1_SAN_IP" -a -z "$NODE2_SAN_IP" ]; then
cat <<EOF
ERROR!
NODE1_SAN_IP is specified but NODE2_SAN_IP is empty.
Both values must be set or unset.
This will cause error. Aborting.
EOF
  exit 1
 fi
 cat <<EOF
Node 2 name: $NODE2_NAME
Node 2 IP: $NODE2_IP
EOF
 test -n "$NODE2_SAN_IP" && echo Node 2 SAN IP: $NODE2_SAN_IP
 test -n "$NODE2_LAN_IP" && echo Node 2 LAN IP: $NODE2_LAN_IP
else
 cat <<EOF
WARNING!
No second node specified.
Creating SkyCover Infrastructure with on only one node.
All redundancy features will be unavailable!
EOF
fi

echo "Proceed with cluster creation [y/n]?"
read i
if [ "$i" != "y" -a "$i" != "Y" ]; then
 echo Aborted.
 exit 1
fi

echo Refilling sci.conf
sed -i 's/^CLUSTER_NAME=.*/CLUSTER_NAME='"$CLUSTER_NAME"'/' /etc/sci/sci.conf
sed -i 's/^CLUSTER_IP=.*/CLUSTER_IP='"$CLUSTER_IP"'/' /etc/sci/sci.conf
test -n "$NODE1_NAME" && sed -i 's/^NODE1_NAME=.*/NODE1_NAME='"$NODE1_NAME"'/' /etc/sci/sci.conf
test -n "$NODE1_LAN_IP" && sed -i 's/^NODE1_LAN_IP=.*/NODE1_LAN_IP='"$NODE1_LAN_IP"'/' /etc/sci/sci.conf
test -n "$NODE2_NAME" && sed -i 's/^NODE2_NAME=.*/NODE2_NAME='"$NODE2_NAME"'/' /etc/sci/sci.conf
test -n "$NODE2_IP" && sed -i 's/^NODE2_IP=.*/NODE2_IP='"$NODE2_IP"'/' /etc/sci/sci.conf
test -n "$NODE2_LAN_IP" && sed -i 's/^NODE2_LAN_IP=.*/NODE2_LAN_IP='"$NODE2_LAN_IP"'/' /etc/sci/sci.conf

echo Creating empty /root/.ssh
mkdir -p ~/.ssh
chmod 700 ~/.ssh

echo Fullfilling /etc/hosts
cat <<EOF >/etc/hosts
127.0.0.1       localhost

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

# cluster
$CLUSTER_IP	$CLUSTER_NAME.$DOMAIN_NAME $CLUSTER_NAME
# first nodes
$NODE1_IP	$NODE1_NAME.$DOMAIN_NAME $NODE1_NAME
$NODE1_LAN_IP	$NODE1_NAME-lan.$DOMAIN_NAME $NODE1_NAME-lan
EOF

if [ -z "$SINGLE_MODE" ]; then
cat <<EOF >>/etc/hosts
$NODE2_IP	$NODE2_NAME.$DOMAIN_NAME $NODE2_NAME
EOF
fi

echo Fulfilling default /etc/ganeti/networks

# correct variable
NODE1_NETDEV=`echo $NODE1_NETDEV|cut -d ':' -f 1`
NODE1_LAN_NETDEV=`echo $NODE1_LAN_NETDEV|cut -d ':' -f 1`

for_networks $NODE1_IP $NODE1_MASK $NODE1_NETDEV >/etc/ganeti/networks
if [ -n "$NODE1_SAN_IP" ]; then
  for_networks $NODE1_SAN_IP $NODE1_SAN_MASK >>/etc/ganeti/networks
fi
if [ -n "$NODE1_LAN_IP" ]; then
  for_networks $NODE1_LAN_IP $NODE1_LAN_MASK $NODE1_LAN_NETDEV >>/etc/ganeti/networks
fi

# create vnc password
#vncpasswd=`pwgen -1`
#echo "Set random vnc password for cluster: $vncpasswd"
#echo $vncpasswd > /etc/ganeti/vnc-cluster-password
echo '' > /etc/ganeti/vnc-cluster-password
chmod 640 /etc/ganeti/vnc-cluster-password
chgrp gnt-daemons /etc/ganeti/vnc-cluster-password
if [ -e /opt/sci-web/sci_webinterface/auth_settings.py ]; then
	sed -i "s/vncpassword//" /opt/sci-web/sci_webinterface/auth_settings.py
fi

echo add sci repo in apt sources
cp /root/sci-dev.list /etc/apt/sources.list.d

echo Initializing cluster
if [ -n "$NODE1_SAN_IP" ]; then
 SECONDARY_IP="-s $NODE1_SAN_IP"
fi
gnt-cluster init --enabled-hypervisors=xen-pvm,xen-hvm --nic-parameters link=`echo $LAN_NETDEV|cut -d ':' -f 1` --master-netdev `echo $MASTER_NETDEV|cut -d ':' -f 1` $SECONDARY_IP $CLUSTER_NAME
test $? -eq 0 || (echo Something wrong on cluster init; exit 1)

echo Tuning cluster
gnt-cluster modify --hypervisor-parameters xen-pvm:bootloader_path=/usr/lib/xen/bin/pygrub,use_bootloader=True,bootloader_args='',kernel_path="/vmlinuz",initrd_path="/initrd.img",root_path='',xen_cmd=xl --reserved-lvs="$RESERVED_VOLS"
test $? -eq 0 || (echo Something wrong on xen pvm modify; exit 1)
gnt-cluster modify --hypervisor-parameters xen-hvm:use_localtime=true,kernel_path=/usr/lib/xen/boot/hvmloader,device_model=/usr/bin/qemu-system-x86_64,xen_cmd=xl,migration_mode=live,vnc_bind_address=127.0.0.1
test $? -eq 0 || (echo Something wrong on xen hvm modify; exit 1)
gnt-cluster modify --ipolicy-bounds-specs=min:disk-size=0,cpu-count=1,disk-count=0,memory-size=1,nic-count=0,spindle-use=0/max:disk-size=4192256,cpu-count=128,disk-count=32,memory-size=1048576,nic-count=32,spindle-use=12
test $? -eq 0 || (echo Something wrong on ipolicy modify; exit 1)
gnt-cluster modify -D drbd:resync-rate=61440,c-max-rate=0,c-min-rate=0,dynamic-resync=False,c-plan-ahead=0,disk-custom='--c-plan-ahead 0',net-custom='--max-buffers 16384 --max-epoch-size 16384'
test $? -eq 0 || (echo Something wrong on drbd modify; exit 1)
gnt-cluster modify -B memory=512M
test $? -eq 0 || (echo Something wrong on default instance parameters modify; exit 1)


# generate rapi password for sci webinterface
rapipasswd=`pwgen -1`
touch /var/lib/ganeti/rapi/users
chmod 640 /var/lib/ganeti/rapi/users
chown gnt-rapi:gnt-masterd /var/lib/ganeti/rapi/users
echo "scweb $rapipasswd write" > /var/lib/ganeti/rapi/users
if [ -e /opt/sci-web/sci_webinterface/auth_settings.py ]; then
	sed -i "s/scpassword/$rapipasswd/" /opt/sci-web/sci_webinterface/auth_settings.py
fi
# generati htpasswd file for mond
touch /etc/sci/sci-mond.htpasswd
chmod 600 /etc/sci/sci-mond.htpasswd
chown www-data /etc/sci/sci-mond.htpasswd
echo "$rapipasswd"|htpasswd -i -c /etc/sci/sci-mond.htpasswd sci-mond


invoke-rc.d uwsgi restart


# tuning lvm filter. if you don't use md, comment it
if (pvs|grep xenvg|grep -q md) then
        sed -i 's/filter = \[ \"a\/\.\*\/\" \]/filter = \[ \"a\/md\/\"\, \"r\/\.\*\/\" \]/' /etc/lvm/lvm.conf
fi

if [ -n "$NODE2_IP" ]; then
 echo Adding the second node
 if [ -n "$NODE2_SAN_IP" ]; then
  SECONDARY_IP="-s $NODE2_SAN_IP"
 fi
 echo "$NODE2_IP       $NODE2_NAME.$DOMAIN_NAME $NODE2_NAME" >>/etc/hosts
 gnt-node add $SECONDARY_IP $NODE2_NAME
 # NOTE: /etc/ganeti/networks is copied by a node-add-post hook to any new node
else
 echo "WARNING! Creating SkyCover Infrastructure with on only one node. This is strongly not recommended for production use!"
fi

test $? -eq 0 || (echo Something wrong; exit 1)

echo Verify
gnt-cluster verify

gnt-node list

;;

show)
cat /etc/sci/sci.conf

;;

xenvg)
cat <<EOF
Sorry, but this operation is not supported yet.

To create xenvg, use the following scheme:

vgcreate xenvg /dev/DEVICE_OF_YOUR_CHOICE
lvcreate -L 20G -n system-stuff xenvg
mkfs.ext4 /dev/xenvg/system-stuff
mount /dev/xenvg/system-stuff /mnt
mv /stuff/* /mnt
umount /mnt
# add "/dev/xenvg/system-stuff /stuff ext4 errors=remount-ro 0 0"
# into /etc/fstab just BEFORE mount of /media/sci
mount /stuff 
EOF

;;

interlink|backbone)

shift
while getopts "fs" opt; do
  case $opt in
    f)
        remove_old_backbone=yes
    ;;
    s)
        SINGLE_MODE="yes"
    ;;
  esac
done

nodenum=`echo $hostname|sed -E 's/^[^.]*[^0-9]([0-9]+)\.?.*/\1/'`
if echo "$nodenum"|grep -q '[^0-9]'; then
 echo Node name must ends with number 1 to 90. Please reinstall.
 exit 1
fi
if [ -z "$nodenum" -o "$nodenum" -lt 0 -o "$nodenum" -gt 90 ]; then
 echo Node name must ends with number 1 to 90. Please reinstall.
 exit 1
fi
if grep -q "^auto backbone" /etc/network/interfaces; then
  if [ -z "$remove_old_backbone" ]; then
    echo Backbone interface already configured.
    exit
  else
    ifdown backbone
  fi
fi

echo Node number: $nodenum

ifs=$target/etc/network/interfaces

# LAN interface: the one the current node IP (NODE1_IP from sci.conf) is up on.
# More reliable than the first bridge_ports in interfaces (which, once backbone
# is written, points at the backbone port, not the LAN).
lanif=`check_ip $NODE1_IP|awk '{print $1}'`
echo LAN interface: $lanif

# Candidate list: real Ethernet interfaces only (whitelist en*/eth*),
# excluding anything with a '.' or '@' (vlan/macvlan aliases), lo, and the LAN.
# Virtual types (bridge/bond/veth/tun/usb/wifi/...) do not match en*/eth* and
# are dropped automatically.
CANDS=`ip -o link show|awk -F':[ \t]*' -vlanif="$lanif" '
  $2 ~ /^(en|eth)/ && $2 !~ /[.@]/ && $2 != "lo" && $2 != lanif {print $2}
'`
echo Candidate interfaces: $CANDS

if [ -z "$SINGLE_MODE" ]; then

# Bring the candidate interfaces up so the physical link (carrier) can be
# detected, then wait for the link to come up.
echo Bringing candidate interfaces up:
for testif in $CANDS; do
 echo "  $testif"
 ifconfig $testif up
done
echo Waiting 30 seconds for links to be up
sleep 32

# Among the candidates, find the one with a physical link up (UP flag set and
# NO-CARRIER absent) — that is where the backbone cable is plugged in.
br0=`ip link show|awk -F':[ \t]*' -vlanif="$lanif" -vcands="$CANDS" '
  BEGIN{ n=split(cands, C, " ") }
  {
    for(k=1; k<=n; k++){ if($2==C[k]){ cand=1; break } }
    if(!cand) next
    cand=0
    if($3 ~ /UP/ && $3 !~ /NO-CARRIER/){
      if(found){ i="toomany"; extra=extra" "$2; exit }
      i=$2; found=1
    }
  }
  END{ if(i=="toomany") print i; else if(found) print i; else print "none" }
'`

if [ "$br0" = "toomany" ]; then
  echo Too many interfaces have a physical link up: $extra.
  echo You should disconnect all but LAN and backbone. Aborting.
  exit 1
elif [ "$br0" = "none" ]; then
  echo No candidate interface has a physical link up.
  echo The backbone cable should be plugged into another server or a powered-on switch. Aborting.
  exit 1
fi

# Bring the other candidate interfaces down, keeping only the detected backbone.
echo Bringing the other candidate interfaces down:
for testif in $CANDS; do
 if [ "$testif" != "$br0" ]; then
  ifconfig $testif down
 fi
done

else
  br0=stubif
fi #SINGLE_MODE

echo Backbone interface: $br0

# remove backbone interfaces
# XXX probably we should better stop here and request -force
awk '/^auto backbone/{exit}//{print}' $ifs >$ifs.new

cat <<EOF >>$ifs.new

auto backbone
iface backbone inet static
        address 10.101.200.$((10+$nodenum))
        netmask 255.255.255.0
        network 10.101.200.0
        broadcast 10.101.200.255
        bridge_ports $br0
        bridge_stp off
        bridge_fd 0

#	up ifconfig $br0 mtu 9000
#	up ifconfig backbone mtu 9000
EOF

mv $ifs.new $ifs

echo Up and test backbone
ifup backbone
if ifconfig backbone|grep "inet 10.101.200.$((10+$nodenum))"; then
    echo ok.
else
    echo Interface backbone not UP. Something wrong. Aborting.
    exit 1
fi

;;

*)

usage

;;

esac
