#! /bin/bash
# -*- coding: utf-8 -*-

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

set -e

out=$1
arch=x86_64

# create the cloud-init iso
init_dir=$(mktemp -d)
meta_data="$init_dir/meta-data"
user_data="$init_dir/user-data"
iso_image="cloud-init.iso"

vm_user="root"
vm_pass="foobar"
key_pub=`cat identity.pub`
host_key=`sed  's/^/    /' host_key`
host_key_pub=`cat host_key.pub`

mkdir -p $init_dir

# We don't want to hardcode values:
# local-hostname: we want multiple instances of the vm to run in parallel
# instance-id: cloud-init skips some init stuff if this is constant (e.g. runcmd)
cat >$meta_data <<EOF
EOF

cat >$user_data <<EOF
#cloud-config
users:
  - default
  - name: ${vm_user}
    groups: users,wheel
    ssh_authorized_keys:
      - ${key_pub}
  - name: admin
    gecos: Administrator
    groups: users,wheel
    ssh_authorized_keys:
      - ${key_pub}
ssh_pwauth: True
chpasswd:
  list: |
    ${vm_user}:${vm_pass}
    admin:${vm_pass}
  expire: False
ssh_keys:
  rsa_private: |
${host_key}
  rsa_public: ${host_key_pub}

# make sure that our user script runs on every boot
cloud_final_modules:
 - scripts-per-once
 - scripts-per-boot
 - scripts-per-instance
 - [scripts-user, always]
 - final-message

# we may need to ping something on the network to update the arp cache
runcmd:
  - while ! ifconfig | grep -q 10\.111\.; do sleep .1; done; ping -W 1s -c 3 10.111.112.1 || true

EOF

genisoimage -input-charset utf-8 -output $iso_image -volid cidata -joliet -rock $user_data $meta_data
