#!/bin/sh -e

if [ "$1" = "configure" ]; then
    if ! getent group nova > /dev/null 2>&1; then
        addgroup --system nova >/dev/null
    fi

    if ! getent passwd nova > /dev/null 2>&1; then
        adduser --system --home /var/lib/nova --ingroup nova --no-create-home --shell /bin/false nova
    fi

    if [ "$(id -gn nova)"  = "nogroup" ]; then
      usermod -g nova nova
    fi

    if [ -z "$2" ]; then
      # New install - blanket permissions
      chown -R nova:nova /var/lib/nova/
    elif dpkg --compare-versions "$2" lt "2011.3-0ubuntu4"; then
      # make sure that LXC rootfs mount points are excleuded
      # during upgrades from previous versions
      find /var/lib/nova/ -name 'rootfs' -prune -o \
        -group root -a -user nova -exec chown nova:nova {} \;
      find /var/lib/nova/ -name 'rootfs' -prune -o \
        -group nogroup -a -user nova -exec chown nova:nova {} \;
    elif dpkg --compare-versions "$2" lt "2012.2~f1~20120503.13935-0ubuntu1"; then
      # convert the /etc/nova/nova.conf to the new configuration
      mv /etc/nova/nova.conf /etc/nova/nova.conf.upgrade
      nova-manage config convert --infile=/etc/nova/nova.conf.upgrade \
        --outfile=/etc/nova/nova.conf
      chmod 600 /etc/nova/nova.conf
      chown nova:nova /etc/nova/nova.conf
      # nova.conf, too (if its there)
      if [ -e /etc/nova/nova-compute.conf ] ; then
        mv /etc/nova/nova-compute.conf /etc/nova/nova-compute.conf.upgrade
        nova-manage config convert --infile=/etc/nova/nova-compute.conf.upgrade \
          --outfile=/etc/nova/nova-compute.conf  
      fi
    fi	

    if [ "$(id -gn nova)"  = "nogroup" ]; then
        usermod -g nova nova
    fi

    if dpkg --compare-versions "$2" lt "2012.1~e3-0ubuntu2"; then
      usermod -s "/bin/false" nova
    fi

    chown -R nova:nova /var/log/nova/ /etc/nova/

    if [ -z "$2" ]; then
        # New install - blanket permissions
        chown -R nova:nova /var/lib/nova/
    elif dpkg --compare-versions "$2" lt "2011.3-0ubuntu4"; then
        # Make sure the LXC rootfs mount points are excluded
        # during upgrades from previous versions
        find /var/lib/nova/ -name 'rootfs' -prune -o \
           -group root -a -user nova -exec chown nova:nova {} \;
        find /var/lib/nova/ -name 'rootfs' -prune -o \
           -group nogroup -a -user nova -exec chown nova:nova {} \;
    fi

    chmod 0600 /etc/nova/nova.conf
    chmod 0600 /etc/nova/policy.json
    chmod 0600 /etc/nova/api-paste.ini
    chmod 0700 /etc/nova
    chmod 0440 /etc/sudoers.d/nova_sudoers
    chmod 0700 /var/log/nova

    if ! grep -q sql_connection /etc/nova/nova.conf
    then
      su -s /bin/sh -c 'nova-manage db sync' nova
    fi

    if [ -e /var/lib/nova/nova.sqlite ]
    then
      chown nova:nova /var/lib/nova/nova.sqlite
      chmod 0600 /var/lib/nova/nova.sqlite
    fi

fi

#DEBHELPER#
