#!/bin/bash
# $Revision: 1.4 $
# By http://en.opensuse.org/User:Mvidner
# Can be called zypp_sa or zypp_sd

ZYPPDIR=/var/lib/zypp
CHANDIR="$ZYPPDIR/db/sources"

if [ "$1" = "--dry-run" ]; then
    shift
    echo Dry run
    DO=echo
fi

hashit() {
    echo -n "$@" | md5sum | cut '-d ' -f1
}

# #245355#c7
xml_escape() {
    local TMP="$1"
    TMP="${TMP//&/&amp;}" # & goes first!
    TMP="${TMP//</&lt;}"
    echo "$TMP"
}

# add source to yast via hack-script
# sa URL [ALIAS [TYPE [REFRESH [ENABLED]]]]
zypp_sa() {
    URL="$1"
    ALIAS="${2-$1}"
    TYPE="${3-YUM}"
    REFRESH="${4-true}"
    ENABLED="${5-true}"
    CACHEDIR=$(mktemp -d "$ZYPPDIR/cache/Source.XXXXXX") || exit 1
    $DO chmod 755 "$CACHEDIR"
    HASH=$(hashit "$ALIAS")
    FILE="$CHANDIR/$HASH"
    if [ "$DO" = echo ]; then
	echo "$FILE":
	FILE=/dev/stdout
	trap "echo -n 'Dry run undo: '; rmdir -v $CACHEDIR" EXIT
    fi
    cat <<END >"$FILE"
<?xml version="1.0" encoding="UTF-8"?>
<source xmlns="http://www.novell.com/metadata/zypp/xml-store">
  <enabled>$ENABLED</enabled>
  <auto-refresh>$REFRESH</auto-refresh>
  <product-dir>/</product-dir>
  <cache-dir>$CACHEDIR</cache-dir>
  <type>$TYPE</type>
  <url>$(xml_escape "$URL")</url>
  <alias>$(xml_escape "$ALIAS")</alias>
</source>
END
}

remove() {
    $DO rm "$@"
}

# sd [--loose-auth] [--loose-query] ALIAS|URL
zypp_sd() {
    LOOSE_AUTH=false
    if [ "$1" = "--loose-auth" ]; then
	LOOSE_AUTH=true
	shift
    fi
    LOOSE_QUERY=false
    if [ "$1" = "--loose-query" ]; then
	LOOSE_QUERY=true
	shift
    fi
    ID="$1"

    HASH=$(hashit "$ID")
    FILE="$CHANDIR/$HASH"
    if [ ! -f "$FILE" ]; then
	# TODO NOW regex-escape ID. but why does it seem to work with $RCE?

	# add anchor to match at end of ID
	# (it will be in the middle of the grepped string, so cannot use $)
	ID="${ID}<"
	if $LOOSE_AUTH; then
	    # replace a string matching the regex by the regex itself
	    RX="//\([^@:]*:[^@]*@\)\{0,1\}"
	    ID=$(echo "$ID" | sed "s|$RX|${RX//\\/\\\\}|")
	fi
	if $LOOSE_QUERY; then
	    # use anchor
	    # replace a string matching the regex by the regex itself
	    RX='\(\?[^?]*\)\{0,1\}<'
	    ID=$(echo "$ID" | sed "s|$RX|${RX//\\/\\\\}|")
	fi
	# remove anchor
	ID="${ID%<}"
	FILE=$(grep -l "<url>$(xml_escape "$ID")</url>" "$CHANDIR"/* )
	if [ ! -f "$FILE" ]; then
	    echo "Not found: $ID" >&2
	    exit 2
	fi
    fi
    # $FILE exists

    CACHEDIR=$(sed -n 's@.*<cache-dir>\([^<]*\)</cache-dir>.*@\1@;T;p;q' "$FILE")
    remove -rf "$CACHEDIR"
    remove "$FILE"
}

if [ ! -r "$CHANDIR" ]; then
    echo "Cannot read $CHANDIR. Try being root." >&2
    exit 1
fi

case "$0" in
    *sa) zypp_sa "$@";;
    *sd) zypp_sd "$@";;
esac
