#!/bin/bash
# Copyright 2010 Novell, Inc.
# Author: Peter Bowen <pzb@novell.com> as a work made for hire
#
#  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.

FLAGS="$1"
DATA=/usr/share/suse-ec2

echo "Configuring system for EC2"

if [ ! -d $DATA ] ; then
	echo "Configuration data not found" >&2
	exit 1
fi

if [ $(uname -s) != "Linux" ]; then
	echo "Configuration script only supports Linux" >&2
	exit 2
fi

##function: fillFile
function fillFile() {
	srcfile="$1"
	dstfile="$2"

	if [ ! -f "$DATA/$srcfile" ]; then
		echo "Configuration file source $srcfile not found; skipping"
		return 1
	fi

	dstfile_dir=$(dirname "$dstfile")
	if [ ! -d "$dstfile_dir" ]; then
		echo "Configuration file destination directory $dstfile_dir not found; skipping"
		return 2
	fi

    echo "Filling $dstfile from $DATA/$srcfile"
	cat "$DATA/$srcfile" > "$dstfile"
}


##function: fillDir
function fillDir() {
	srcdir="$1"
	dstdir="$2"

	if [ ! -d "$DATA/$srcdir" ]; then
		echo "Configuration file source $srcdir not found; skipping"
		return 1
	fi

	if [ ! -d "$dstdir" ]; then
		echo "Configuration directory destination $dstdir not found; skipping"
		return 2
	fi

	ls "$DATA/$srcdir" | while read N; do
        echo "Filling $dstdir directory from $DATA/$srcdir/$N"
		cp -dR "$DATA/$srcdir/$N" "$dstdir"
	done
}

##function: sysconfig_has_key
function sysconfig_has_key() {
    S='[[:space:]]*'
    grep -E -q "^$S$2$S=$S" "$1"
    return $?
}

##function: sysconfig_set_key
function sysconfig_set_key() {
    S='[[:space:]]*'
    sed -i -r -e "s%^($S$2$S=$S).*%\1\"$3\"%" "$1"
}

##function: sysconfig_add_key
function sysconfig_add_key() {
    echo "$2=\"$3\"" >> "$1"
}

##function: sysconfig_ensure_key
function sysconfig_ensure_key() {
    if sysconfig_has_key "$1" "$2"; then
        sysconfig_set_key "$1" "$2" "$3"
    else
        sysconfig_add_key "$1" "$2" "$3"
    fi
}

# Change SSH policies
echo "Changing SSH policies"
sed -r -i -e 's@^#?PermitRootLogin[[:space:]].*@PermitRootLogin without-password@;s@^#?UseDNS[[:space:]].*@UseDNS no@' /etc/ssh/sshd_config
# Set a random strong root password
echo "Setting a random root password"
head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c 40 | passwd --stdin root
# Have DHCP Set the hostname
echo "Configuring DHCP"
sysconfig_set_key /etc/sysconfig/network/dhcp DHCLIENT_SET_HOSTNAME yes
# Disable persistent network card names (will not work with rebundling)
# For SLES10
echo "Disabling persistent network card rules"
sysconfig_set_key /etc/sysconfig/network/config FORCE_PERSISTENT_NAMES no
# Fix ec2-ami-tools library path

# The inittab needs to run getty on the appropriate consoles
echo "Updating inittab: disabling mingetty"
awk '{
  if ($0 ~ /^[^#].*mingetty/) {
    print "# $0"
  } else {
    print
  }
}' /etc/inittab > /etc/inittab.new
cat /etc/inittab.new > /etc/inittab
rm /etc/inittab.new

grep -E -q '^x0:' /etc/inittab
if [ $? -eq 0 ]; then
  echo "Updating inittab: resetting agetty"
  sed -i -e 's@^x0:.*@x0:12345:respawn:/sbin/agetty -L 9600 xvc0 vt102@' /etc/inittab
else
  echo "Updating inittab: enabling agetty"
  awk '{
    if ($0 ~/\/agetty/) {
        print $0 "\nx0:12345:respawn:/sbin/agetty -L 9600 xvc0 vt102"
    } else {
        print
    }
  }' /etc/inittab > /etc/inittab.new
  cat /etc/inittab.new > /etc/inittab
  rm /etc/inittab.new
fi

# Disable IPv6
echo "Disabling IPv6"
##FIXME: wrong filename on SLE10
echo 'install ipv6 /bin/true' > /etc/modprobe.d/50-ipv6.conf
sysconfig_ensure_key /etc/sysconfig/windowmanager KDE_USE_IPV6 no

# eth0 should be configured
echo "Configuring eth0"
fillFile ifcfg-eth0 /etc/sysconfig/network/ifcfg-eth0


# the default fstab varies by arch
echo "Updating fstab"
machine=$(uname -m) 	
case "$machine" in
	i?86)
        arch=i386
		;;
	x86_64)
        arch=x86_64
		;;
	*)
        echo "Unknown architecture: $machine"
		;;
esac

fillFile fstab.$arch /etc/fstab

# Enable amazon service
insserv amazon
insserv amazon-late

distpkg=$(rpm -qf --qf '%{NAME}' /etc/SuSE-release)
case "$distpkg" in
	open*)
		dist=''
		;;
	sle*)
		dist='sle'
		;;
	*)
		echo "Unknown distribution"
		;;
esac

distver=$(rpm -qf --qf '%{VERSION}' /etc/SuSE-release | sed -e 's/\.//g')
dist="${dist}${distver}"
		

echo "Updating motd"
fillFile motd.$dist.$arch /etc/motd

# Configure zypper repositories
# Clean and refresh zypper cache unless --norefresh option was given
echo "Configuring zypper"
fillDir zypp-sources.$dist.$arch /var/lib/zypp/db/sources
fillDir services.d.$dist.$arch /etc/zypp/services.d
fillDir repos.d.$dist.$arch /etc/zypp/repos.d

#SLE10 zypper does not make cache directories if they are missing
if [ -d /var/lib/zypp/db/sources ]; then
    echo "Making zypp cache directories"
    grep -h -F '<cache-dir>' /var/lib/zypp/db/sources/* \
    | sed -e 's@^.*<cache-dir>@@;s@</cache-dir>@@' \
    | while read -r D; do
        mkdir -vp "$D"
    done
fi

echo "$FLAGS" | grep -q -- "--norefresh" || { 
	zypper clean --all
	zypper refresh --force
}

##private function: cleanup_tdir
function cleanup_tdir {
	[ "$TDIR" -a -d "$TDIR" ] && rm -rf "$TDIR"
}

trap cleanup_tdir INT TERM

# Add missing gpg keys to rpm
echo "Adding GPG keys to RPM"
TDIR=$(mktemp -d)
if [ -d "$TDIR" ]; then
	pushd "$TDIR"
    # Yes, this is in /usr/lib on x86_64
	/usr/lib/rpm/gnupg/dumpsigs /usr/lib/rpm/gnupg/suse-build-key.gpg
	ls gpg-pubkey-*.asc | while read KFN; do
		KEY=$(basename "$KFN" .asc)
		rpm -q "$KEY" >/dev/null
		[ $? -eq 0 ] && continue
		echo "Importing $KEY"
		rpm --import "$KFN"
	done
	popd
	rm -rf "$TDIR"
else
	echo "Could not create temp directory"
fi
