#!/bin/sh

URL="https://slink-auth.secioss.com"
CONFURL="https://s3-ap-northeast-1.amazonaws.com/slink-conf/public/rp"

TSFILE=/usr/local/etc/updatehttpd
HOST=`sed -n "s/^ServerName \([^:]*\)/\1/p" /etc/httpd/conf/httpd.conf`
TENANT=`sed -n "s#^ *'https://[^/]*/\([^']*\)' => .*#\1#p" /opt/secioss/share/simplesamlphp/metadata/saml20-idp-remote.php`

UPDATE=
CTS=`date +'%s'`
wget --no-check-certificate -O /tmp/updatehttpd $URL/conf/${HOST}_${TENANT}
TS=`cat /tmp/updatehttpd`
PTS=
if [ -f $TSFILE ]; then
    PTS=`cat $TSFILE`
    if [ $PTS -lt $TS ]; then
        UPDATE=1
    fi
else
    UPDATE=1
fi

if [ "$UPDATE" ]; then
    filename=`echo -n ${HOST}_${TENANT} | openssl sha1`.zip
    wget --no-check-certificate -O /tmp/$filename $CONFURL/$filename
    if [ ! -f /tmp/$filename ]; then
        echo "Can't download config files from $CONFURL/$filename"
        exit 1
    fi
    unzip /tmp/$filename -d /tmp/

    rm -f /etc/httpd/sso-ssl/*.conf
    cp -r /tmp/${HOST}_${TENANT}/* /
    rm -rf /tmp/${HOST}_${TENANT}
    echo '<?php' > /opt/secioss/share/simplesamlphp/metadata/saml20-sp-hosted.php
    echo '$metadata = array(' >> /opt/secioss/share/simplesamlphp/metadata/saml20-sp-hosted.php
    url=https://$HOST
    for file in `find /etc/httpd/sso-ssl -name "*.conf"`; do
        path=`cat $file | sed -n 's#^<LocationMatch "\([^(]*\)[^"]*">#\1#p' | sed 's#/$##'`
        echo "        '$url$path' => array(
                'host'  => '$HOST$path',
                'NameIDFormat' => null
        )," >> /opt/secioss/share/simplesamlphp/metadata/saml20-sp-hosted.php
    done
    echo ");
?>" >> /opt/secioss/share/simplesamlphp/metadata/saml20-sp-hosted.php

    /etc/init.d/httpd graceful
fi

echo $CTS > $TSFILE
