#!/bin/bash
set -e

# SECURITY WARNING
# generated file project.cfg may contain credentials used to access 
# https://cesg.canonical.com/${CESGDIR}/
# Therefor it must be deleted (and must not be in bzr):
trap 'rm -f project.cfg' SIGINT EXIT

# check whether project.cfg.in contains cesg.credentials, and if so, warn and stop;
if $(grep -q "@cesg.canonical.com" project.cfg.in) ; then
    echo -e "\nError: project.cfg.in appears to contain user credentials for cesg.canonical.com"
    echo "This is a potential security leak. Instead the URL should not contain the credentials"
    echo "and the username and password should be entered as prompted during ./update execution."
    echo "These credentials should not exist in any file that is commited to the branch."
    echo -e "Stopping.\n"
    exit 1
fi

# ensure required executables/pkgs installed
if ! which dch >/dev/null; then
    echo >&2 "please install devscripts"
    exit 1
fi

if ! which debootstrap >/dev/null; then
    echo >&2 "please install debootstrap"
    exit 1
fi

# if project.cfg.in uses cesg.canonical, obtain credentials via zenity gtk pop-ups
# generate project.cfg from project.cfg.in

# If you want to build the meta pkg from a -devel archive located in a dedicated 
# directory like this: cesg.canonical.com/charlotte/ instead of from the typical
# cesg.canonical.com/canonical/, then change CESGDIR to the dir name:
CESGDIR='canonical'

ARCHIVE="archive_base/default:\ https://cesg.canonical.com/${CESGDIR}/"

# fix cesg subdir name per CESGDIR in project.cfg.in
sed -i "s+archive_base/default:\ https://cesg.canonical.com/canonical/+${ARCHIVE}+g" project.cfg.in

# Query for username and password to access for cesg
CREDS="See:\nhttps://wiki.canonical.com/PES/Infrastructure/Repository/CustomerMirrors"

if $(grep -q ^"${ARCHIVE}" project.cfg.in) ; then
    username=$(zenity --entry --title="Username" --text="${CREDS}")
    password=$(zenity --entry --title="Password" --text="${CREDS}")
    if [ -z "$username" ] || [ -z "$password" ]; then
        echo "Error. Username and password required when the project.cfg.in file includes https://cesg.canonical.com/${CESGDIR}. Stopping."
        exit 1
    else
        # make project.cfg with cesg credentials
        sed "s_https://cesg.canonical.com/${CESGDIR}_https://${username}:${password}@cesg.canonical.com/${CESGDIR}_g" project.cfg.in > project.cfg
    fi

else
    # make project.cfg without cesg credentials
    cp project.cfg.in project.cfg
fi

./oem-meta.py && germinate-update-metapackage --bzr

exit 0
