#!/bin/bash

#
# jats-repos-el6
# ==============
#
# This script enables COPR repositories for JATS (Juat A Test System) on older
# yum/rpm-based repositories that don't yet have COPR plugin: that is, CentOS 6
# and RHEL 6.
#
# This is roughly equivalent to calling following on newer distros:
#
#     yum install yum-plugin-copr
#     yum copr enable netvor/shellfu
#     yum copr enable netvor/jats
#
# except that it is INSECURE, ie. will DISABLE SSL and DISABLE GPG CHECK.
# That is, use this only for throw-away testing machines.
#
#
# About
# -----
#
# Version: 0.0.1
# Author: https://netvor.info/
# Licence: GPL v2
#

die() {
    echo "fatal: $1" >&2
    exit 3
}

think() {
    echo "$1" >&2
}

get_url() {
    #
    # Print url for repo $Repo
    #
    case $Repo in
        netvor/jats)
            echo "https://copr.fedorainfracloud.org/coprs/netvor/jats/repo/epel-6/netvor-jats-epel-6.repo"
            ;;
        netvor/shellfu)
            echo "https://copr.fedorainfracloud.org/coprs/netvor/shellfu/repo/epel-6/netvor-shellfu-epel-6.repo"
            ;;
    esac
}

disable_gpgcheck() {
    #
    # Make sure gpgcheck is disabled in repo file $1
    #
    local file=$1
    local without
    think "disabling gpgcheck for: $fname"
    without=$(grep -wv gpgcheck "$file")
    {
        echo "$without"
        echo gpgcheck=0
    } >"$file"
}

disable_sslverify() {
    #
    # Make sure sslverify is disabled in repo file $1
    #
    local file=$1
    local without
    think "disabling sslverify for: $fname"
    without=$(grep -wv sslverify "$file")
    {
        echo "$without"
        echo sslverify=0
    } >"$file"
}

main() {
    local cfdir=/etc/yum.repos.d
    local Repo
    local fname
    local url
    which curl >&/dev/null \
     || die "this script needs curl"
    test -d "$cfdir" >&/dev/null \
     || die "this script needs yum-based distro"
    test "$(id -u)" -eq 0 \
     || die "this script needs to run as root"
    cd /etc/yum.repos.d \
     || die "could not chdir: $cfdir"
    for Repo in netvor/shellfu netvor/jats; do
        url=$(get_url) \
         || die
        fname=${url##*/}
        think "downloading: $Repo"
        curl -s --insecure -f "$url" >"$fname" \
         || die "failed to download: $url"
        disable_sslverify "$fname" \
         || die
        disable_gpgcheck "$fname" \
         || die
    done
}

main "$@"
