#!/bin/bash
set -euo pipefail
# Script that either checks for an attached USB stick which has an RPM repo on
# it (with option -c) or adds it without any options if it can be added.

CHECK_TOGGLED=1
while getopts ":c" opt; do
  case $opt in
    c)
      CHECK_TOGGLED=0
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done


# Search through all mounted usb devices for the directory 'repodata'
IFS=$'\n'
found_centos_repodata=0
for mountsline in `cat /proc/self/mounts`; do
  device=`echo $mountsline | cut -f 1 -d ' '`
  set +e
  udevline=`udevadm info -q path -n $device 2>&1 | grep usb` # detect USB disks
  is_iso9660=`echo "$mountsline" | grep iso9660` # detect the ISO9660 fs
  set -e
  if [ "$udevline" != "" ] || [ "$is_iso9660" != "" ]; then
    usbpath=`echo $mountsline | cut -f 2 -d ' ' | sed "s|\\\\\\040| |g"`
    centos_repodata="$usbpath/repodata"
    if [ -d "$centos_repodata" ] ; then
       found_centos_repodata=1
       break;
    fi
  fi
done


if [ "$found_centos_repodata" -eq "0" ]; then
  echo "No repo found!" >&2
  exit 1
fi

if [ "$CHECK_TOGGLED" -eq "0" ]; then
  echo "Repo found from '$usbpath'." >&2
  exit 0
fi


# Create the repo file in /etc/yum.repos.d
REPO_CENTOS_BASE_OFFLINE_PATH="/etc/yum.repos.d/base-offline.repo"
REPO_CENTOS_BASE_OFFLINE_URL="file://$(echo "$usbpath" | sed 's| |%20|g')"

rm -fv "$REPO_CENTOS_BASE_OFFLINE_PATH"

cat > "$REPO_CENTOS_BASE_OFFLINE_PATH" <<EOC
[base-offline]
name=CentOS base offline
baseurl=${REPO_CENTOS_BASE_OFFLINE_URL}
enabled=1
gpgcheck=0
EOC

chown -v root:root "$REPO_CENTOS_BASE_OFFLINE_PATH"
chmod -v 644 "$REPO_CENTOS_BASE_OFFLINE_PATH"

echo "Repo-file created in '$REPO_CENTOS_BASE_OFFLINE_PATH'." >&2
