#!/bin/sh

if [ ! $(whoami) = "root" ]; then
  echo "You need to be root to run this command."
  exit 1
fi

RUNNING_FREEBSD_VERSION=$(uname -r | awk -F '-' '{print $1}')
RUNNING_FREEBSD_ARCH=$(uname -m)

case ${RUNNING_FREEBSD_VERSION} in
  "10.3") ;;
  "11.1") ;;
  "11.2") ;;
  "12.1") ;;
  *)
    echo "Unsupported FreeBSD version \"${RUNNING_FREEBSD_VERSION}\"."
    exit 1
  ;;
esac

run_command() {

  #############################################################################
  ## This function exists for two reasons; 1) to give better feedback to the ##
  ## user and 2) provide a rudimentary form of error checking to just bail   ##
  ## out if things go south.                                                 ##
  ##                                                                         ##
  ## Two important things to know about it.                                  ##
  ## - Always remember to begin and end the command you want to have run     ##
  ## with quotation marks to have it passed through as just one long string. ##
  ## - Any quotation marks inside the command have to be commented out by    ##
  ## prefixing with a backslash so that they pass through "echo" as literal  ##
  ## quotes. Example:                                                        ##
  ## run_command "echo \"\""                                                 ##
  ## To pass through those same characters but literally(\"):                ##
  ## run_command "echo \\\"\\\""                                             ##
  #############################################################################

  RUN_DIR="/var/tmp"
  if [ ! -d ${RUN_DIR} ]; then
    mkdir ${RUN_DIR}
    chown root:$(id root | awk '{gsub(/\(/, " "); gsub(/\)/, " "); if ($3 ~ "gid") print $4}') ${RUN_DIR}
    chmod 777 ${RUN_DIR}
  fi
  COMMAND=$(mktemp ${RUN_DIR}/run_command.cmd.XXXXXX)
  OUTPUT=$(mktemp ${RUN_DIR}/run_command.out.XXXXXX)
  echo "#!/bin/sh" > ${COMMAND}
  echo "$1" >> ${COMMAND}
  chmod +x ${COMMAND}
  echo "+-- Running command:"
  echo "$(cat ${COMMAND} | egrep -v "^#!/bin/sh$")"
  ${COMMAND} > ${OUTPUT} 2>&1
  if [ $? -gt "0" ]; then
    echo "+-- Command Failed!"
    echo "+-- Output was:"
    echo "$(cat ${OUTPUT})"
    echo ""
    rm ${OUTPUT} > /dev/null 2>&1
    rm ${COMMAND} > /dev/null 2>&1
    exit 1
  else
    echo "+-- Command succeeded."
    echo ""
  fi
  rm ${OUTPUT} > /dev/null 2>&1
  rm ${COMMAND} > /dev/null 2>&1
}

run_command "env ASSUME_ALWAYS_YES=YES pkg bootstrap"

if ! grep -q 'WITH_PKGNG="YES"' /etc/make.conf 2>/dev/null; then
  run_command "echo 'WITH_PKGNG=\"YES\"' >>/etc/make.conf"
fi

if [ -f /var/db/pkg/pkgdb.db ]; then
  run_command "pkg2ng"
fi

if [ -f /etc/pkg/FreeBSD.conf ]; then
  if grep -q 'enabled: yes' /etc/pkg/FreeBSD.conf 2>/dev/null; then
    run_command "sed -i '' 's/enabled: yes/enabled: no/' /etc/pkg/FreeBSD.conf"
  fi
fi

if [ ! -d /usr/local/etc/ssl/certs ]; then
  run_command "mkdir -p /usr/local/etc/ssl/certs"
fi

if [ ! -f /usr/local/etc/ssl/certs/pkg.cert ]; then
  run_command "cat > /usr/local/etc/ssl/certs/builder.cert << EOF
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAq0kf3rq8ZjFJu27QAovb
dzDULSbroYaYqIur5q0+atl+GUAglX63EbO8vfwuu43Fy6Ai+UN84J7mnm71fu5u
1SwBLd1ZYSECr4aD6KlupS7HlN2T99KYD7kEH2ezumWbc210Y3+ZK/XSDyo3uRBy
aMXnPofZG1fifG3mzatEAF/yPBPram+C2EM5TUoWbrBAI5LudCUHrmolQ9FGz15O
JEbHxbWPBcpck9FUKq6w5pWEoukmoo8RXMrcPNFA3BOSH2yw10oghap+hqQWoCxd
Q5M7hTjKJZfPObn68PLkNYH6ugoiBIL3FeVlJXH1ZoWpvhP4LuYJVwuNd/MM60MP
7oe4qm+767ziIBd7wsQujQjbOczVxmetP6MQwEoShf3TG3QawDlbu8prf0VIyVrR
0awlC8mmJfYmz/Ku33BRXfvAOCESTlt8ZiMHuSn5eKnUfHtsKbKlNr8PD1rrpuKn
1Xn7FRr6bmCVmAVkG6uyfFUoLm+LTJGOt4pECc3MwOl6ZhqTG1hKTxPpF/G9pF0e
waBP6Ty0ZUidL10SSP5Dcs1gKSSNFJ082o/jgJjARPYvc3RyhJb0Khl9G5kxbQFQ
QccQxdWrd1CiDxgBwFANnIDhuI7PPxe3wbQ/EoS7C4fD2HQwr5hjq/gKDFltCpab
VogiYNRkVid+G93l+8ZxHpkCAwEAAQ==
-----END PUBLIC KEY-----
EOF"
fi

if [ ! -f /usr/local/etc/pkg.conf ]; then
  run_command "cat > /usr/local/etc/pkg.conf << EOF
REPO_AUTOUPDATE     : YES
ALIAS               : {
  all-depends: query %dn-%dv,
  annotations: info -A,
  build-depends: info -qd,
  download: fetch,
  iinfo: info -i -g -x,
  isearch: search -i -g -x,
  leaf: query -e \"%a == 0\" \"%n-%v\",
  leaf: query -e \"%a == 0\" \"%n-%v\",
  list: info -ql,
  origin: info -qo,
  provided-depends: info -qb,
  raw: info -R,
  required-depends: info -qr,
  shared-depends: info -qB,
  show: info -f -k,
  size: info -sq,
  }
EOF"
fi

REPOS_DIR="/usr/local/etc/pkg/repos"

if [ ! -d ${REPOS_DIR} ]; then
  run_command "mkdir -p ${REPOS_DIR}"
fi

if [ ! -f ${REPOS_DIR}/builder.conf ]; then
  run_command "echo 'builder: {' > ${REPOS_DIR}/builder.conf"
  case "${RUNNING_FREEBSD_VERSION}" in
    "10.3")
      run_command "echo '    url             : \"http://builder.inparadise.se/repo/release103amd64-default\",' >> ${REPOS_DIR}/builder.conf"
    ;;
    "11.1")
      run_command "echo '    url             : \"http://builder.inparadise.se/repo/release111amd64-default\",' >> ${REPOS_DIR}/builder.conf"
    ;;
    "11.2")
      run_command "echo '    url             : \"http://builder.inparadise.se/repo/release112amd64-default\",' >> ${REPOS_DIR}/builder.conf"
    ;;
    "12.1")
      run_command "echo '    url             : \"http://builder.inparadise.se/repo/release121amd64-default\",' >> ${REPOS_DIR}/builder.conf"
    ;;
  esac
  run_command "cat >> ${REPOS_DIR}/builder.conf << EOF
    signature_type  : \"PUBKEY\",
    pubkey          : \"/usr/local/etc/ssl/certs/builder.cert\",
    enabled         : yes,
    mirror_type     : NONE,
}
EOF"
fi

if [ -f ${REPOS_DIR}/FreeBSD.conf ]; then
  if grep -q 'enabled: yes' ${REPOS_DIR}/FreeBSD.conf 2>/dev/null; then
    run_command "sed -i '' 's/enabled: yes/enabled: no/' ${REPOS_DIR}/FreeBSD.conf"
  fi
else
  run_command "echo 'FreeBSD: { enabled: no }' > ${REPOS_DIR}/FreeBSD.conf"
fi

run_command "pkg update -f"
run_command "pkg upgrade -fy pkg"
run_command "pkg check -Ba"
