#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"

# Clear boot up flag, it would be created by rc.local after boot up done
mkdir -p /var/cache/cloud
rm -f /var/cache/cloud/boot_up_done

[ -x /sbin/ifup ] || exit 0

. /lib/lsb/init-functions

log_it() {
  echo "$(date) $@" >> /var/log/cloud.log
  log_action_msg "$@"
}

patch() {
  local PATCH_MOUNT=/media/cdrom
  local patchfile=$PATCH_MOUNT/cloud-scripts.tgz
  local privkey=$PATCH_MOUNT/authorized_keys
  local md5file=/var/cache/cloud/cloud-scripts-signature
  local cdrom_dev=
  mkdir -p $PATCH_MOUNT

  if [ -e /dev/xvdd ]; then
       cdrom_dev=/dev/xvdd
  elif [ -e /dev/cdrom ]; then
       cdrom_dev=/dev/cdrom
  elif [ -e /dev/cdrom1 ]; then
       cdrom_dev=/dev/cdrom1
  elif [ -e /dev/cdrom2 ]; then
       cdrom_dev=/dev/cdrom2
  elif [ -e /dev/cdrom3 ]; then
       cdrom_dev=/dev/cdrom3
  fi

  if [ -f /var/cache/cloud/authorized_keys ]; then
    privkey=/var/cache/cloud/authorized_keys
  fi

  if [ -n "$cdrom_dev" ]; then
    mount -o ro $cdrom_dev $PATCH_MOUNT
    local oldmd5=
    [ -f ${md5file} ] && oldmd5=$(cat ${md5file})
    local newmd5=
    [ -f ${patchfile} ] && newmd5=$(md5sum ${patchfile} | awk '{print $1}')

    log_it "Scripts checksum detected: oldmd5=$oldmd5 newmd5=$newmd5"
    if [ "$oldmd5" != "$newmd5" ] && [ -f ${patchfile} ] && [ "$newmd5" != "" ]
    then
      tar xzf $patchfile -C /
      echo ${newmd5} > ${md5file}
      log_it "Patched scripts using $patchfile"
      touch /var/cache/cloud/patch.required
    fi

    if [ -f $privkey ]; then
      cp -f $privkey /root/.ssh/
      chmod go-rwx /root/.ssh/authorized_keys
    fi
  fi

  return 0
}

start() {
  log_it "Executing cloud-early-config"

  # Clear /tmp for file lock
  rm -f /tmp/*.lock
  rm -f /tmp/rrouter_bumped
  rm -f /root/.rnd
  echo "" > /root/.ssh/known_hosts

  patch
  sync
  /opt/cloud/bin/setup/bootstrap.sh

  log_it "Finished setting up systemvm"
  exit 0
}

start
