#!/bin/bash

ME=$(basename $0);

source //etc/common-utils.rc;
source //etc/ec2.rc;

function metastrap()
{
    cat > $metastrap_out <<EOF
#!/bin/bash

function set_ec2_creds()
{
    cat > $EC2_CERT <<EOF_CERT
$(cat $EC2_CERT)
EOF_CERT

    cat > $EC2_PRIVATE_KEY <<EOF_PK
$(cat $EC2_PRIVATE_KEY)
EOF_PK
}


function set_ssh_keys()
{
    mkdir -p /root/.ssh;

    cat > /root/.ssh/gluster <<EOF_PRIV
$(cat /root/.ssh/gluster)
EOF_PRIV

    cat > /root/.ssh/gluster.pub <<EOF_PUB
$(cat /root/.ssh/gluster.pub)
EOF_PUB

    cat /root/.ssh/gluster.pub >> /root/.ssh/authorized_keys;
    cat /root/.ssh/gluster > /root/.ssh/id_rsa;
    chmod 600 /root/.ssh/id_rsa;
}


function set_domain()
{
    echo $DOMAIN > //etc/domain;
}


function upgrade_repo()
{
    if [ -s //etc/domain ]; then
        return;
    fi
    yum clean all;
    if which gluster-app-migrate ; then
        yum update -y;
        gluster-app-migrate $(cat //etc/GlusterFS-VERSION 2>/dev/null);
    else
        gluster-repo-switch $(cat //etc/GlusterFS-VERSION 2>/dev/null);
    fi
    service glusterd start;
}

function main()
{
    source /etc/profile.d/ec2.sh
    source /etc/profile.d/java.sh
    source /etc/profile.d/gluster-env.sh
    source /etc/profile.d/gluster-ami.sh
    set_ec2_creds;
    set_ssh_keys;
    upgrade_repo;
    set_domain;
}

main "\$@";
EOF
}


function show_help()
{
    usage_banner;
    cat <<EOF

Usage:  $ME [-h] PROGOUT

Generate PROGOUT file used in user-data tag of new instance

WARNING: This is an internal tool.  You should not invoke this
         directly.  Refer gluster-ami-newinstance tool for more
         detail.

Miscellaneous:
  -h                        display this help and exit

Example:
  $ME /tmp/tag-content.txt
EOF
}


function main()
{
    # Parse command line arguments.
    while getopts :h OPT; do
	case "$OPT" in
	    h)
		show_help
		exit 0
		;;
	    \?)
                # getopts issues an error message
		echo "Invalid option: -$OPTARG"
		show_help
		exit 1
		;;
	esac
    done

    # Remove the switches we parsed above.
    shift `expr $OPTIND - 1`

    # We want only one non-option argument.
    if [ $# -ne 1 ]; then
	show_help
	exit 1
    fi

    if [ -f $1 ]; then
        fail "$1 already exists";
    fi

    metastrap_out=$1;

    metastrap;
}

main "$@";
