91c4d5070be14d8fef3b36bf39f02803634c28fb
[matthijs/servers/drsnuggles.git] / usr / local / bin / vserver-create
1 #!/bin/sh
2
3 TEMPLATE=template
4 VSERVERS_CONF=/etc/vservers
5 EXCLUDE_FILE="$VSERVERS_CONF/clone-exclude"
6 IP_RANGE=10.42.0.
7 INTERFACE=dummy0
8 NETMASK=24
9
10 function usage()
11 {
12         echo "Usage: $0 name"
13         echo "Creates a new vserver with the specified name, which is a clone"
14         echo "from the vserver \`\`$TEMPLATE'' with some post-processing done."
15 }
16
17 function find_ip()
18 {
19         IP_FILES="$VSERVERS_CONF/*/interfaces/*/ip"
20         for i in {2..53}; do
21                 IP=${IP_RANGE}$i
22                 if ! grep ^$IP$ $IP_FILES &>/dev/null; then
23                         return 0
24                 fi
25         done
26         return 1
27 }
28
29 # Check arguments
30 if [ ! "$#" -eq 1 ]; then
31         usage
32         exit 1
33 fi
34
35 NAME=$1
36
37 if ! echo $NAME | grep "^[a-zA-Z0-9-]*$" &>/dev/null; then
38         echo "Name can only contain alphanumerics and dashes"
39         exit 1
40 fi
41
42 HOST="$NAME/`hostname --fqdn`"
43
44 # Set the IP var
45 if ! find_ip; then
46         echo "No available ip address found, aborting"
47         exit 1
48 fi;
49
50 echo "Creating vserver $NAME with address $IP..."
51 sudo vserver $NAME build -m clone --hostname $HOST --interface $INTERFACE:$IP/$NETMASK -- --source $TEMPLATE --exclude-from $EXCLUDE_FILE
52
53 echo "Vserver created, configuring..."
54 sudo vserver $NAME start
55 # Regen ssh keys
56 sudo vserver $NAME exec dpkg-reconfigure openssh-server
57 # Setup git - Add a branch for this vserver
58 sudo vserver $NAME exec git branch $NAME origin/$TEMPLATE
59 sudo vserver $NAME exec git checkout $NAME
60 # Remove the template branch, to prevent pushing it back later on 
61 sudo vserver $NAME exec git branch -d $TEMPLATE
62 # Push our new branch upstream so it can be pushed with "git push" afterwards.
63 sudo vserver $NAME exec git push origin $NAME:$NAME
64 # Enable vhashify/vunify
65 sudo mkdir $VSERVER_CONF/$NAME/apps/vunify
66 sudo touch $VSERVER_CONF/$NAME/apps/vunify/dummy # For git
67
68 # Remove trailing slashes from the confdir. git only works when we're using
69 # relative paths and the cwd is / for some reason...
70 CONF_FOR_GIT=`echo $VSERVERS_CONF/$NAME | sed "s#^/*##"`
71 # Commit the configuration
72 (cd /; git add $CONF_FOR_GIT)
73 (cd /; git commit $CONF_FOR_GIT --edit --message "vserver: Add $NAME vserver configuration.")