#!/bin/sh -e

# This is a very hacky script to generate satellites.
# A honestly shitty attempt to auto-generate satellites.

astronaut="$(dirname "$0")/astronaut"
[ ! -f "$astronaut" ] && astronaut="astronaut"

# TODO: These variables won't always be valid
dir_build="$PWD/build"
dir_source="$PWD/source"
dir_install="$PWD/install"

tempdir="/tmp/internaut"
rm -rf "$tempdir"
mkdir -p "$tempdir"

intshell() {
    # This is the most hacky part in the script, so bear with me.
    # Why this is even a thing, is because I need two things:
    # - Run some commands on start
    # - Capture all input
    # I'm sure "tee ouput | bash --rcfile filewithcommands" would effectively do the same thing, but fuck bash.

    echo "Entering shell..."

    cmdfifo="$tempdir/cmdfifo"
    waitfifo="$tempdir/waitfifo"
    mkfifo "$cmdfifo" 2> /dev/null || true
    mkfifo "$waitfifo" 2> /dev/null || true

    sh -s < "$cmdfifo" "$pkgfile" &
    shpid=$!

    echo ". \"$astronaut\"; set +e; echo \$PWD > \"$waitfifo\"; cat \"$waitfifo\"" > "$cmdfifo"
    while ps -p $shpid > /dev/null; do
        printf "$(cat "$waitfifo")> "
        read cmd

        case "$cmd" in
            exit) ;;
            !*) cmd="$(echo "$cmd" | cut -c 2-)" ;;
            *) echo "$cmd" >> "$pkgfile" ;;
        esac

        echo "$cmd" > "$cmdfifo"

        echo "echo \$PWD > \"$waitfifo\"; cat \"$waitfifo\"" > "$cmdfifo"
        printf '' > "$waitfifo"
    done

    rm -f "$waitfifo" "$cmdfifo"
    echo 'End shell.'
}

# The rest of this script is your olde gather info stuff.

printf 'Package name: '
read pkgname
pkgfile="$PWD/$pkgname.sat"

echo "# Generated with internaut. Please revise and edit." > "$pkgfile"
echo >> "$pkgfile"

printf 'Software name [enter for same as package]: '
read name
if [ "$name" ]; then
    echo "name=$name" >> "$pkgfile"
else
    echo "name=$pkgname" >> "$pkgfile"
fi

printf 'Version: '
read version
echo "version=$version" >> "$pkgfile"

printf 'Update URL: '
read update_url
echo "update_url=\"$update_url\"" >> "$pkgfile"

echo >> "$pkgfile"

# Now we ask the user to fetch the files they need.
echo '=> Header'
intshell

# Generate the md5sums, append them to the satellite, for manual inspection.
for file in $(find "$dir_source" -type f); do
    printf '# ' >> "$pkgfile"
    md5sum "$file" >> "$pkgfile"
done

printf 'header_end\n\n' >> "$pkgfile"

# Now we ask the user to build and install the program in question.
echo '=> Build'
intshell

# Replacing all the instances of the name and the version with the variable.
#sed -i -e "s/$name/\$name/g" -e "s/$version/\$version/g" -e "s/name=\$name/name=$name/g" -e "s/version=\$version/version=$version/g" "$pkgfile"
# TODO: Why dun dis shit work?

# The usual vim config line.
printf '\n# vim:set tabstop=4 shiftwidth=4 syntax=sh et:\n' >> "$pkgfile"

rm -rf "$tempdir"