#!/bin/sh
#    Copyright 2015 Mirantis, Inc.
#
#    Licensed 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.

# NOTE(kozhukalov): This script is needed only for 6.1.
# We are going to download debian-installer initrd and kernel just
# before starting actual provisioning and then put them where they
# will be available for cobbler.

set -eu

SCRIPT_NAME=`basename $0`
LOG_FILE="/var/log/${SCRIPT_NAME}.log"
LOCK_FILE="/var/lock/${SCRIPT_NAME}.lock"

usage(){
    echo "Usage: ${SCRIPT_NAME} <kernel_uri> <initrd_uri>"
    exit 1
}

lock(){
    exec 200>$1
    flock -w 600 -x 200 || return 1
    return 0
}

log(){
    echo "`date '+%Y-%m-%d %H:%M:%S'` $$ $1" | tee -a $LOG_FILE
}

log "Checking if another instance of ${SCRIPT_NAME} is running."
lock $LOCK_FILE || { log "Error: Another instance of ${SCRIPT_NAME} is running \
at the moment. Please try later." 1>&2 ; exit 1; }

log "Checking if all necessary command line arguments are available."
test $# -eq 2 || usage

REMOTE_KERNEL_URI=$1
REMOTE_INITRD_URI=$2
LOCAL_KERNEL_FILE=${LOCAL_KERNEL_FILE:-/var/www/nailgun/ubuntu/x86_64/images/linux}
LOCAL_INITRD_FILE=${LOCAL_INITRD_FILE:-/var/www/nailgun/ubuntu/x86_64/images/initrd.gz}

log "Trying to download $REMOTE_KERNEL_URI"
mkdir -p `dirname $LOCAL_KERNEL_FILE`
wget -O - -T 120 -a $LOG_FILE -v $REMOTE_KERNEL_URI > $LOCAL_KERNEL_FILE.tmp

log "Trying to download $REMOTE_INITRD_URI"
mkdir -p `dirname $LOCAL_INITRD_FILE`
wget -O - -T 120 -a $LOG_FILE -v $REMOTE_INITRD_URI > $LOCAL_INITRD_FILE.tmp

mv $LOCAL_KERNEL_FILE.tmp $LOCAL_KERNEL_FILE
mv $LOCAL_INITRD_FILE.tmp $LOCAL_INITRD_FILE
