#!/bin/bash
#
# This source file is Copyright (c) 2019, FERMI NATIONAL ACCELERATOR
#    LABORATORY.  All rights reserved.
# For details of the Fermitools (BSD) license see COPYING.

if [ ! -f /etc/cvmfs-user-pub.conf ]; then
    exit
fi

PREFIX="`sed -n 's/^prefix\s*//p' /etc/cvmfs-user-pub.conf`"
if [ -z "$PREFIX" ]; then
    PREFIX=sw
fi
MYHOSTLONG="`hostname`"
MYHOSTSHORT="`hostname -s`"

OTHERHOST=""
for HOSTREPO in `sed -n 's/^hostrepo\s*//p' /etc/cvmfs-user-pub.conf`; do
    HOST="`echo $HOSTREPO|sed 's/:.*//'`"
    if [ "$HOST" != "$MYHOSTLONG" ] && [ "$HOST" != "$MYHOSTSHORT" ]; then
        if [[ $HOST == *.* ]]; then
            OTHERHOST=$HOST
        else
            OTHERHOST=$HOST${MYHOSTLONG#"$MYHOSTSHORT"}
        fi
    fi
done

ADDEDONE=false
for HOSTREPO in `sed -n 's/^hostrepo\s*//p' /etc/cvmfs-user-pub.conf`; do
    HOST="`echo $HOSTREPO|sed 's/:.*//'`"
    REPO="`echo $HOSTREPO|sed 's/.*://'`"
    if [ -d /etc/cvmfs/repositories.d/$REPO ]; then
        continue
    fi

    if [ "$HOST" = "$MYHOSTLONG" ] || [ "$HOST" = "$MYHOSTSHORT" ]; then
        MYREPO=true
    else
        MYREPO=false
    fi

    if [ -d /srv/cvmfs/$REPO ]; then
        # data previously existed, save it to re-use
        if [ -d /srv/cvmfs/.$REPO.SAV ]; then
            echo "Refusing to overwrite saved data, skipping $REPO"
            continue
        fi
        echo "Saving /srv/cvmfs/$REPO in /srv/cvfs/.$REPO.SAV"
        mv /srv/cvmfs/$REPO /srv/cvmfs/.$REPO.SAV
    fi

    REPOPUB=/etc/cvmfs/keys/$REPO.pub
    DOMAIN="`echo $REPO|cut -d. -f2-`"
    if [ ! -f $REPOPUB ]; then
        REPOPUB=""
    fi
    PUB=/etc/cvmfs/keys/$DOMAIN.pub
    if [ ! -f $PUB ]; then
        PUB=/etc/cvmfs/keys/$DOMAIN/$DOMAIN.pub
        if [ ! -f $PUB ]; then
            if [ -z "$REPOPUB" ]; then
                echo "No key found for $REPO"
                continue
            fi
            PUB=""
        fi
    fi
    if [ -n "$REPOPUB" ] && [ -n "$PUB" ]; then
        PUB=":$PUB"
    fi
    PUB="$REPOPUB$PUB"
    ADDEDONE=true

    if [ $MYREPO ]; then
        REPHOST=$OTHERHOST
    else
        REPHOST=$HOST
    fi
    echo "Adding replica $REPO from $REPHOST"
    if ! cvmfs_server add-replica -o cvmfspub http://$REPHOST/cvmfs/$REPO $PUB; then
        echo "Failed to add-replica $REPO from $REPHOST with key $PUB"
        if ! $MYREPO; then
            continue
        fi
        # make sure that the repo really doesn't exist on the other host
        #  so as to not overwrite it if it failed for another reason
        if curl -sf http://$REPHOST/cvmfs/$REPO/.cvmfswhitelist >/dev/null; then
            echo "Source repo does appear to exist on $REPHOST, so skipping"
            continue
        fi
    fi
    if [ -d /srv/cvmfs/.$REPO.SAV ]; then
        echo "Restoring /srv/cvmfs/$REPO from /srv/cvfs/.$REPO.SAV"
        rm -rf /srv/cvmfs/$REPO
        mv /srv/cvmfs/.$REPO.SAV /srv/cvmfs/$REPO
    fi
    if ! cvmfs_server snapshot $REPO; then
        echo "Failed to make initial snapshot of $REPO from $REPHOST"
        if ! $MYREPO; then
            continue
        fi
    fi

    if $MYREPO; then
        if [ -d /etc/cvmfs/repositories.d/$REPO ]; then
            # have now restored a backup from the other host, so
            #  remove the configuration but leave the data
            echo "Removing cvmfs repo configuration for $REPO"
            cvmfs_server rmfs -f -p $REPO
        fi

        echo "Adding repo $REPO"
        if [ -d /srv/cvmfs/$REPO ]; then
            if ! cvmfs_server import -o cvmfspub $REPO; then
                continue
            fi
        elif ! cvmfs_server mkfs -o cvmfspub $REPO; then
            continue
        fi
        touch /srv/cvmfs/$REPO/.cvmfs_master_replica
        ADDEDONE=true
        SERVERCONF=/etc/cvmfs/repositories.d/$REPO/server.conf
        for OPT in  CVMFS_GARBAGE_COLLECTION=true \
                    'CVMFS_AUTO_TAG_TIMESPAN="1 day ago"' \
                    CVMFS_IGNORE_XDIR_HARDLINKS=true \
                    CVMFS_GENERATE_LEGACY_BULK_CHUNKS=false \
                    CVMFS_AUTOCATALOGS=true \
                    CVMFS_ENFORCE_LIMITS=true \
                    CVMFS_FORCE_REMOUNT_WARNING=false \
                    CVMFS_AUTO_GC=false \
                    CVMFS_REPOSITORY_TTL=15 \
                    CVMFS_PRINT_STATISTICS=true \
        ; do
            if ! grep -q "^$OPT$" $SERVERCONF; then
                echo "$OPT" >>$SERVERCONF
            fi
        done
        if ! cvmfs_server transaction $REPO; then
            if [ ! -f /cvmfs/$REPO/.cvmfsdirtab ]; then
                echo "Cannot start transaction, skipping making .cvmfsdirtab"
            else
                echo "Cannot start transaction, skipping initializing gc-ability"
            fi
        else
            if [ ! -f /cvmfs/$REPO/.cvmfsdirtab ]; then
                (echo "/*";
                echo "/$PREFIX/*";
                echo "/ts/*") >/cvmfs/$REPO/.cvmfsdirtab
                chown cvmfspub /cvmfs/$REPO/.cvmfsdirtab
                rm -f /cvmfs/$REPO/new_repository
            fi
            cvmfs_server publish $REPO
        fi
        # Fix common problem seen with reflog
        cvmfs_server check -r $REPO
    fi

    if [ ! -f /srv/cvmfs/$REPO/.htaccess ]; then
        # set up so the other host can replicate from here
        touch /srv/cvmfs/$REPO/.cvmfs_master_replica
        (echo "Order deny,allow"
        echo "Deny from all"
        echo "Allow from 127.0.0.1"
        echo "Allow from $MYHOSTLONG"
        if [ -n "$OTHERHOST" ]; then
            # This is only used for re-installs
            echo "Allow from $OTHERHOST"
        fi
        ) >/srv/cvmfs/$REPO/.htaccess
    fi
done

if $ADDEDONE; then
    systemctl stop cvmfs-user-pub
    systemctl start cvmfs-user-pub
fi

