#!/bin/sh
#    psp.sh, an alternative to asp for working with Parabola (initial draft)
#    Copyright (C) 2021  alicia@ion.nu
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

ttl=3600
repos='libre pcr packages community'
# libre
repo_libre_url='https://git.parabola.nu/abslibre.git'
repo_libre_path='/libre'
# pcr
repo_pcr_url='https://git.parabola.nu/abslibre.git'
repo_pcr_path='/pcr'
# TODO: We assume that the packages in arch's master branches match their individual package branches. Check that this is accurate?
# core, extra, & testing
repo_packages_url='https://github.com/archlinux/svntogit-packages.git'
repo_packages_path=''
# community & multilib
repo_community_url='https://github.com/archlinux/svntogit-community.git'
repo_community_path=''
updaterepo()
{
  gitname="`basename "$1"`"
  repopath="$2"
  reponame="$3"
  if [ ! -e "${HOME}/.local/var/psp/git/${gitname}" ]; then
    mkdir -p "${HOME}/.local/var/psp/git"
    # TODO: Option to clone full depth? Could be useful for package history, but takes a lot of space
    git clone --depth 1 "$1" "${HOME}/.local/var/psp/git/${gitname}" && \
    date '+%s' > "${HOME}/.local/var/psp/git/${gitname}/.timestamp"
  else
    oldtime="`cat "${HOME}/.local/var/psp/git/${gitname}/.timestamp"`"
    time="`date '+%s'`"
    if [ "`expr "$oldtime" + "$ttl"`" -lt "$time" ]; then
echo "Updating ${reponame}"
      (cd "${HOME}/.local/var/psp/git/${gitname}" && git pull) && \
      echo "$time" > "${HOME}/.local/var/psp/git/${gitname}/.timestamp"
    fi
  fi
  mkdir -p "${HOME}/.local/var/psp/repos"
  ln -s "../git/${gitname}${repopath}" "${HOME}/.local/var/psp/repos/${reponame}" 2> /dev/null
}
getvar(){ eval "echo \"\$${1}\""; }
package="$1"
for repo in ${repos}; do
  url="`getvar "repo_${repo}_url"`"
  path="`getvar "repo_${repo}_path"`"
  updaterepo "$url" "$path" "$repo"
  repodir="${HOME}/.local/var/psp/git/`basename "$url"`"
  if [ -d "${repodir}${path}/${package}" ]; then
    if [ -f "${repodir}${path}/${package}/PKGBUILD" ]; then
      dir="${repodir}${path}/${package}"
    elif [ -f "${repodir}${path}/${package}/trunk/PKGBUILD" ]; then
      dir="${repodir}${path}/${package}/trunk"
    else break; fi
    echo "Found '${package}' in ${repo}"
    ln -s "$dir" "$package"
    exit
  fi
done
echo "Package '${package}' not found"
