#!/bin/sh
search=false
list=''
nodepend=''
update=false

helptext()
{
  echo "Usage: $0 [options] <packagename>"
  echo
  echo "$0 fetches build-instructions from the AOS BuildWiki"
  echo " (https://aos.ion.nu/buildwiki/) and tries to resolve"
  echo " dependencies."
  echo "You may wish to pipe the output to sh -e"
  echo ""
  echo "Options include:"
  echo "-s, --search    = search for packages by name"
  echo "-l, --list      = only list dependencies"
  echo "-n, --nodepend  = generate instructions without regard for already"
  echo "                                      installed dependencies."
  echo "-u, --update    = install newer versions of already installed packages."
  echo "--sourcedir ... = build someplace other than ${HOME}/.local/src"
  exit 1
}

installed="" # packages to avoid getting instructions for because their instructions have already been printed
sourcedir="${HOME}/.local/src"
pkg=""
while [ "$#" -gt "0" ]; do
  case "$1" in
  -s|--search) search=true;;
  -l|--list) list='-l';;
  -n|--nodepend) nodepend='-n';;
  -u|--update) update=true;;
  --sourcedir) shift; sourcedir="$1";;
  --internal_installedpackages) shift; installed="$1";;
  -*) helptext;;
  *) pkg="$1";;
  esac
  shift
done
if [ "$pkg" = "" ] && ! "$update"; then helptext; fi

if [ ! -e "${HOME}/.local/etc/installedpackages" ] && [ "$nodepend" = "" ]; then
  pkgs="`(ls /usr/parent-src; ls /usr/src; ls "$sourcedir") 2> /dev/null | grep '[-_]' | sed -e 's/[-\.].*//;/_/{p;s/_/-/;}' | sort -u`"
  mkdir -p "${HOME}/.local/etc"
  if [ "$pkgs" != "" ] && ! echo "$pkgs" > "${HOME}/.local/etc/installedpackages"; then
    echo "# ${HOME}/.local/etc/installedpackages does not exist and it could not be automatically generated"
    exit 1
  fi
fi

if "$search"; then
  content="`wget --post-data="page=${pkg}" --max-redirect=0 -q -O - "https://aos.ion.nu/buildwiki_findpage.php"`"
  if [ "$content" = "" ]; then
    echo "${pkg} (perfect match)"
  else
    echo "$content" | sed -e 's/<a/\n&/g' | sed -n -e 's/<a href="buildwiki[^>]*>\([^<]*\)<.*/\1/p'
  fi
  exit 0
fi

if "$update" && [ "$pkg" = "" ]; then
  handled=''
  sed -e 's/ .*//' "${HOME}/.local/etc/installedpackages" | while read pkg; do
    if echo "$handled" | grep -q -x -F "$pkg"; then continue; fi
    handled="${handled}
${pkg}"
    "$0" -u ${list} "$pkg"
  done
  exit 0
fi

expr='/<pre>/,/<\/pre>/{s/.*<pre>//;s/<\/pre>.*//;s/<[^>]*>//g;s/&lt;/</g;p;}'
content="`wget -q -O - "https://aos.ion.nu/buildwiki/${pkg}.html" | sed -n -e "$expr"`"
version="`echo "$content" | sha1sum`"
if "$update"; then
  if [ "$content" = "" ]; then exit 0; fi # Ignore installed packages that do not have a page in the buildwiki
  oldversion="`sed -n -e "s/^${pkg} //p" "${HOME}/.local/etc/installedpackages" | tail -n 1`"
  if [ "$oldversion" = "$version" ]; then exit 0; fi
  dir="`echo "$content" | sed -n -e '/^ *cd /{s/^ *cd //; s/ *#.*//; p; q;}'`"
  if [ -e "${sourcedir}/${dir}" -o -e "/usr/parent-src/${dir}" ]; then
    exit 0
  fi
fi
if [ "$content" = "" ]; then echo "false # Not found"; exit 1; fi
for x in `echo "$content" | sed -n -e '/^# Note: depends on [^ ]/{s/^# Note: depends on //;s/[ #].*//;p;}'`; do
  if [ "$list" = "" ]; then
    echo "# Detected dependency '$x'"
  fi
  if [ "$nodepend" = "" ] && grep -q "^$x"'\(\| .*\)$' "${HOME}/.local/etc/installedpackages"; then
    if [ "$list" = "" ]; then echo "# Already installed"; fi
  else
    if ! echo "$installed" | grep -q "{${x}}"; then
      [ "$list" != "" ] || echo "if ! grep -q '^${x}\(\| .*\)\$' "${HOME}/.local/etc/installedpackages"; then"
      instructions="`"$0" ${list} ${nodepend} --internal_installedpackages "{} $installed" "$x"`"
      if echo "$installed" | grep -q '{}'; then
        echo "$instructions"
      else
        echo "$instructions" | sed -e '/^WIKI2SHELLNOTE:/d'
      fi
      installed="${installed} `echo "$instructions" | sed -n -e 's/^WIKI2SHELLNOTE://p;' | sed -e 's/.*/{&}/;'`"
      [ "$list" != "" ] || echo "fi"
    fi
  fi
done
if echo "$installed" | grep -q '{}'; then
  echo "WIKI2SHELLNOTE:$pkg"
fi
[ "$list" != "" ] || echo "mkdir -p ${sourcedir}; cd ${sourcedir}" # Assume we'll build it here
content="`echo "$content" | sed -e 's/^useradd [^#]*/& || true /'`" # Don't fail because a user already exists
if [ "`whoami`" != "root" ]; then # Run 'make install' etc. as root (the <&2 is to take stdin from stderr so su won't complain about stdin not being a tty)
  # make install
  runwithsu="s/ *# *(*as root.*//; s/\\\\/\\\\&/g; s/\"/\\\\&/g; s/\`/\\\\&/g; s/\\\$/\\\\&/g; s/.*/(echo \"Running su for: &\"; su -c \"&\" <\&2)/"
  content="`echo "$content" | sed -e "/^ *\(make\|ninja\) .*install.*/{${runwithsu};}"`"
  # mkdir -p /absolute/path
  expr="/^ *mkdir -p [\"']\?\/.*/"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # cp file /absolute/path
  expr="/^ *cp \(-[^ ]* \|\)[^ ]* \/.*/"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # ln * /absolute/path
  expr="/^ *ln .* \\/[^ ]*\$/"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # fc-cache
  content="`echo "$content" | sed -e "/^ *fc-cache$/{${runwithsu};}"`"
  # addtoconfig > /etc/file
  expr="/^.*> \/etc\/.*/"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # addtofile > /usr/*
  expr="/^.*> \/usr\/.*/"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # groupadd
  content="`echo "$content" | sed -e "/^ *groupadd .*/{${runwithsu};}"`"
  # useradd
  content="`echo "$content" | sed -e "/^ *useradd .*/{${runwithsu};}"`"
  # install
  content="`echo "$content" | sed -e "/^ *install .*/{${runwithsu};}"`"
  # anything marked with "as root"
  content="`echo "$content" | sed -e "/^.*# *(*as root)*\(,.*\|\)\$/{${runwithsu};}"`"
  # xmlcatalog
  content="`echo "$content" | sed -e "/xmlcatalog .*/{${runwithsu};}"`"
  # mv origin /absolute/destination
  expr="/^ *mv [^ ]* \/.*/" # {s/'/\"/g;s/.*/(echo 'Running su for: &'; su -c '&' <\&2)/;}"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # scons install
  content="`echo "$content" | sed -e "/^ *scons .*install.*/{${runwithsu};}"`"
  # chown
  content="`echo "$content" | sed -e "/^ *chown /{${runwithsu};}"`"
  # chmod
  expr="/^ *chmod .* \//"
  content="`echo "$content" | sed -e "${expr}{${runwithsu};}"`"
  # for (not actually run as root, but may need some tweaking)
  expr="s/^ *for \([a-zA-Z0-9]*\) .*; *do/& export \1;/"
  content="`echo "$content" | sed -e "${expr}"`"
fi
# Mirrors
expr=":s;/^ *wget\( \| .* \)-O /{s@.* -O ['\"]*\([^ '\`\"]*\)['\"]* .*@wget -c https://aos.ion.nu/sourcemirror/\1 || &@;n;bs;}; s@^wget .*://[^ ]*/\([^ \`\";'?]*\)[^#]*@wget -c https://aos.ion.nu/sourcemirror/\1 || &@"
content="`echo "$content" | sed -e "${expr}"`"
if [ "$list" = "" ]; then
  echo "$content"
  echo 'if [ "$?" = "0" ]; then echo '"'${pkg} ${version}'"' >> "${HOME}/.local/etc/installedpackages"; fi'
else
  echo "$pkg"
fi
